I was playing around with a WPF app I'm writing for a friend and discovered a need for a single user control to exhibit two distinct sets of behaviors. In practical terms I wanted the user control to display contact data for an individual and a business even though these two entities have unique sets of properties.

I've seen some posts in the WPF forums where people have tried, with varying levels of success, a variation on WinForms forms inheritance using XAML. Having little patience and an aversion to complexity I avoided that approach and jumped into the code-behind for my user control. What if I simply created a new class for each of my entities that simply subclasses the user control? It worked like a charm.

This is a simple matter of exploiting the WPF type system. When I create an instance of my user control in XAML I specify that I want the control to be an instance of one of the derived classes; in this case OwnerContact. WPF understands that OwnerContact is just a class that is derived from ContactInfo, which is the implementation associated with the markup found in ContactInfo.xaml. WPF is able to reach into the base class to extract the information necessary to render the control.

This capability leads to all kinds of possibilities for manipulating the behavior of visual elements in an application. I haven't had a lot of time to play around with this discovery, but I'll follow up this post with some tips and tricks for exploiting this feature in cool and interesting ways.

Technorati Tags: ,,