Wednesday, December 18, 2013

Base Classes and WPF

Well I got far enough into my application's first page to understand how much I can put into a base class. I discovered a gotcha that had me scratching my head for a while, so when I found the solution I thought I better write it down. Here it is...

Let's suppose you have a XAML page, let's call it OrderEntry. Your XAML and code behind will be something like this...
<UserControl x:Class="OrderEntry"..../>
</UserControl>


Public Class OrderEntry
.
.
.
End Class

Now in order to subclass OrderEntry I created a base class called BaseOrderScreens and inherited OrderEntry from the new class. I thought all I would have to do is add an Inherits clause so that the code behind looks like this...

Public Class BaseOrderScreens
    Inherits System.Windows.Controls.UserControl

End Class



Public Class OrderEntry
    Inherits BaseOrderScreens
.
.
.
End Class

But when I made the change and compiled I got a strange error message.
Base class 'System.Windows.Controls.UserControl' specified for class 'OrderEntry' cannot be different from the base class 'BaseOrderScreens' of one of its other partial types.
This is where it gets fun. The error is in the generated partial class OrderEntry.g.vb which is inheriting the partial OrderEntry class from UserControl. My part of the OrderEntry class inherits the class from BaseOrderScreens. The compiler does not allow multiple inheritance so I have to convince the generated code to inherit from BaseOrderScreens. How to do this?

It turns out the generated partial class is inheriting OrderEntry from UserControl because my XAML has a root element with a TagName of UserControl. If the root element was OrderEntry all would be good. I have to modify my XAML to contain a reference to my namespace (see xmlns:local) and then alter the root element. It now looks like this...

<local:BaseOrderScreens x:Class="OrderEntry"
             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:OrderProcessing"
             mc:Ignorable="d" 
             d:DesignHeight="800" d:DesignWidth="1000">
.
.
.
</local:BaseOrderScreens >

To make this even more difficult to figure out, the VS editor highlights the root element name as an error until you compile.

No comments:

Post a Comment