WPF Window inheritance: problems and problems

As I’m fairly new to WPF I’m also fairly naive and I thought that WPF would be more or less over-hyped win forms and that if you wanted to make a base window you could do it like you do it in a win forms project. In a forms project you just create a class, let it inherit from the Form class and then use it as base class.
In WPF it is a bit more tricky.

The first thing I did was to create an entire .XAML file (such as BaseWindow.xaml) with XAML code and everything and then inherit it. That gave me the following error:

Partial declarations of ‘WpfTest.SomeWindow’ must not specify different base classes

You can’t separate the XAML code which sort of makes sense, so you have to create a standard class file only as your base, let it inherit from the Window class and then inherit it in your window .cs file, such as:

public class BaseWindow : Window
{
    protected string m_ImportantField = "Important!";
 
    public BaseWindow()
    {
 
    }
}

(I’ve added a protected field so as to justify this stupid example)

Then you inherit this window instead of the base Window in your presentation:

public partial class Window1 : BaseWindow
{
    public Window1()
    {
        InitializeComponent();
        this.Title = m_ImportantField;
    }
}

Now, given this XAML in your Window1 file,:

<Window x:Class="WpfTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300" xmlns:my="http://schemas.microsoft.com/wpf/2008/toolkit">
    <Grid></Grid>
</Window>

you’ll get these errors:

Partial declarations of ‘WpfTest.Window1’ must not specify different base classes
The name ‘m_ImportantField’ does not exist in the current context

This is because only the back-end code knows about the inheritance. The XAML code will be compiled into C# code as well and if it doesn’t inherit from our BaseWindow class it will of course not compile. So, we need to update the XAML as well:

<base:BaseWindow x:Class="WpfTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:base="clr-namespace:WpfTest"
    Title="Window1" Height="300" Width="300" xmlns:my="http://schemas.microsoft.com/wpf/2008/toolkit">
    <Grid></Grid>
</base:BaseWindow>

We add a new namespace, I call it ‘base’, and add the namespace of our base class. We then change the root of the XAML document to our base class, BaseClass, instead of the standard base class Window.
It should now compile and run, almost as easy as with win forms!

Leave a Reply