'SomeBaseControl' cannot be the root of a XAML file because it was defined using XAML
Now, what can we do to avoid this unpleasant message?
Use a custom control for the base class (defined only with code, not XAML)
This is handy sometimes. What you do is create the base control as a custom control, using just the code
public class TestBaseCtrl : Control
// Add some base logic here...
You can add your controls from the code and create the base logic. Then you can inherit that control even in XAML, like this.
This is a working solution, but it's not very convenient. You don't have the flexibility of XAML in the base control. So let's take a look at the other solution.
Create the base control using XAML
OK, but how on earth do we do that? We all saw the error message - we cannot define a base control in XAML and then inherit it again in XAML, according to the compiler. However, there is an easy way to trick the compiler to allow us to do that.
The main idea is to create a base control as a custom control again, and then define a control template in XAML. It's basically the same as defining the base control with XAML. Here is what I mean. This is the code-behind for the control:
public class TestBaseCtrl : UserControl
public static RoutedCommand TestButton1 = new RoutedCommand();
public static RoutedCommand TestButton2 = new RoutedCommand();
DefaultStyleKeyProperty.OverrideMetadata(typeof(TestBaseCtrl), new FrameworkPropertyMetadata(typeof(TestBaseCtrl)));
this.CommandBindings.Add(new CommandBinding(TestButton1, TestButton1_Executed));
this.CommandBindings.Add(new CommandBinding(TestButton2, TestButton2_Executed));
private void TestButton1_Executed(object sender, ExecutedRoutedEventArgs e)
MessageBox.Show("This is button 1 from the base control");
private void TestButton2_Executed(object sender, ExecutedRoutedEventArgs e)
MessageBox.Show("This is button 2 from the base control");
And this is the control template, defined in XAML:
You can see that we have specified an area of the base control, in which the content of the child controls would be displayed, using ContentPresenter.
Now, let's inherit that control:
Now, the WPF compiler is totally OK with it, and even displays the inherited control in the designer:
And there you go - now you have a base control and an inherited control which both use the power of XAML. Everything goes well in the compilation and the compiler is no longer mad at us:
========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ==========
Download sample application
The sample can be downloaded here: Download sample