Wednesday, April 23, 2014

WPF: Inheriting from custom class instead of Window

In ASP.NET, we learned that it is often interesting to inherit from another class than from System.Web.UI.Page. This allows to define common methods, such as utilities, etc... which are used by a set of web pages throughout an application.
In WPF, it's also possible to do the same, and to inherit from a custom class instead of System.Windows.Window, of System.Windows.Controls.Page, or of System.Windows.Controls.UserControl for example.
When you add a Window (or Page, or UserControl...) to a WPF project, the chain of inheritance is as follows:




If you have a special method "doSomething()" which you want to reuse in every Window in the application, then you can store it in an abstract class GalaSoftLb.Wpf.WindowBase and modify the inheritance as follows:




In the diagrams above, the Window class is the framework's one, and the class GalaSoftLb.Wpf.WindowBase is abstract.
In order to get the new Windows to derive from this abstract class, not only the C# code must be modified, but also the XAML code. This is a little tricky, because a special syntax must be used. Instead of the usual:

<Window x:Class="WindowsApplication1.Window1"
  Title="WindowsApplication1" Height="300" Width="300"
  >
  <Grid>        
  </Grid>
</Window>

We have instead:

<src:WindowBase x:Class="WindowsApplication1.Window1"
  xmlns:src="clr-namespace:GalaSoftLb.Wpf" 
  Title="WindowsApplication1" Height="300" Width="300"
  >
  <Grid>
  </Grid>
</src:WindowBase>