Search code examples
wpfxamluser-controlsuser-defined

User defined top level control in XAML


A normal UserControl looks like this in XAML:

<UserControl x:Class="mynamespace.foo" ...namespaces...>
<!-- content -->
</UserControl>

I'd like to be able to define my own top level object, along the lines of:

<MyControl x:Class="mynamespace.mycontrol" ...namespaces...>
<!-- content -->
</UserControl>

Where MyControl derives from a UserControl itself.

Of course the compiler complains about "MyControl" not being found. Is there a way around this?


Solution

  • The root tag is the base class. That's why the root of the default Window1 is Window. Using the menu option Add > UserContol... is in fact creating a sub-class for UserContol.

    If you have some common elements and want a control base class you can use the base class as the root tag. You can't derive your class from any class that has a xaml defined visual tree, but your base class can derive from UserConrtol.

    First define your base class:

    public class MyControlBase : UserControl
    {
        // ...
    }
    

    Then create your specific child class:

    (You can start with the automatically created UserControl1 and change it from there)

    public partial class MyControl1 : MyControlBase
    {
        public MyControl1()
        {
            InitializeComponent();
        }
    }
    

    Then change the Xaml side to look like this:

    <MyNamespace:MyControlBase
        x:Class="MyNamespace.MyControl1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:MyNamespace="clr-namespace:MyNamespace">
    

    This is a great way to make custom controls derived from built in ones other that UserControl. It is typically recommended to just use basic UserConrtols if you can and make a custom control only if you have to.

    good luck,