Custom base class for WPF-Control

I created CustomControl for my project, and I'm going to create some more. All of these controls will have something in common, so I created an abstract class that inherits from UserControl.

If I create a CustomControl through VisualStudio, it also inherits from UserControl, and I cannot switch it to the abstract abstract UserControl, because VisualStudio will add some generated code files. I do not want to contact these files.

I could just create an empty code file and write everything myself, but then I can’t use XAML (or I don’t know yet).

So, how do I create a CustomControl with a custom base class without losing XAML?

+5
source share
1 answer

Firstly, you cannot easily use abstract classes in the UserControl class hierarchy - it doesn’t work with the designer (you get the message “Unable to instantiate the message“ AbstractBase ”). The same problem, and there were some workarounds, all of which were painful .

After removing the "abstract", you should be able to reference your base class by including the namespace in your XAML definition and changing the code like this:

<local:AbstractBase x:Class="Test.ConcreteControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:Test"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
    </Grid>
</local:AbstractBase>

and

    /// <summary>
    /// Interaction logic for ConcreteControl.xaml
    /// </summary>
    public partial class ConcreteControl : AbstractBase
    {
        public ConcreteControl()
        {
            InitializeComponent();
        }
    }

This assumes your base class is called "AbstractBase"

+12
source

All Articles