How to derive a WPF class from XAML class RRS feed

  • Question


    I have a WPF class which is generated from XAML and relative .cs file. I want to derive a new class based on that. Is it possible?


    If yes, any sample code?

    If no, what's the reason? Is there any workaround for that, like loading XAML at runtime?

    Tuesday, December 11, 2007 9:12 AM


  • Hi Li,


    You can certainly derive from this class... simply create a new Class and go from there.  You won't be able to derive from the class specified by your .xaml and .cs file with another .xaml and .cs pairing because the .xaml file defines the visual tree of the class.  It's hard to imagine how one would "extend" an XML description of visual elements.


    You could however define a concrete base class that encapsulates the functionality that you want shared between your two classes, and have two different .xaml and .xaml.cs files that define the visuals of your windows.  You could even use a style defined at the application resource level to specify the visuals of these classes... since Styles can inherit.  I think this suits the purpose you're going for here.


    To do this:


    1) Declare a class that derives from an allowed type for Xaml root elements:


    Code Block

    public class CustomWindowBase : Window


    public CustomWindowBase() {}

    ... // Shared code all classes need to use...



    2)  For each derived class, declare the .xaml like so:


    Code Block

    <loc:CustomWindowBase x:Class="DerivedChildClass.Window1"




    Title="Window1" Height="300" Width="300" Loaded="Window_Loaded">


    </< FONT><loc:CustomWindowBase>


    Note the parts specified in bold font. 





    Wednesday, December 12, 2007 6:28 PM