27.12.09

Visual inheritance in WPF

My final year .NET project was a medium-weight WPF application which had some 8 windows in all. Creating the windows and customizing the interface in XAML was a breeze with Visual Studio 2008 and Expression Blend 2. Even coding up the window logic was not that tough, but halfway into the logic part, I realized that all my windows had some properties and methods in common. So the code could be shortened a great deal using inheritance.

Basically, the approach is simple. Create a class in a separate code file (say Blindow in Blindow.cs) which inherits from System.Windows.Window, add all the properties and method implementations and virtual methods you need to it, and make all your windows inherit from Blindow. So, our Blindow looks like this:


  1. namespace BlindApp.Windows
  2. {
  3. public class Blindow : Window
  4. {
  5. // all your properties and methods here
  6. }
  7. }


So, the class declarations for all the windows in the application now change from

public partial class Window1 : Window
to

public partial class Window1 : Blindow

All is fine and well, the code should compile correctly, but shockingly, it doesn't and throws up an error. Reason: Forgot the XAML. If you know WPF well, you must realize that the class declaration for Window1 in the codebehind is only partial. The remaining partial declaration lies in the XAML. So, this means one has to come up with a way to let XAML know that Window1 inherits from Blindow now.
The source of the error now lies here

<Window x:Class="BlindApp.Windows.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">


So what we need to do to rectify the error is first add an XML namespace (with any name you like) for the CLR namespace. The CLR namespace for Window1 is BlindApp.Windows, so add a line as follows

<Window x:Class="BlindApp.Windows.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
xmlns:blinder="clr-namespace:BlindApp.Windows">


You don't need to type out the clr-namespace: statement - Visual Studio 2008 provides IntelliSense for that. But, we are not done yet, an error will again pop up because we need to replace the first line itself. Now that the XML namespace has been created, this is how it's done:

<blinder:Blindow x:Class="BlindApp.Windows.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
xmlns:blinder="clr-namespace:BlindApp.Windows">


Just like you could set Resources and Triggers with Window.Resources and Window.Triggers, you can do the same now with <blinder:blindow.resources> and <blinder:blindow.triggers>

No comments:

Post a Comment