Generic UserControl Base Class in Silverlight

Having generics in .NET is a great thing. I already loved template classes in C++, missed them in .NET 1.x, and was happy to get a (little bit restricted) kind of templates in .NET 2.0.

Building a Silverlight application, I felt the need to create a generic UserControl base class. But I was unable to use it until I found the following hint: “Known Issue – Controls Deriving From A Generic Base Class Must Be In Separate Assembly” (http://blogs.msdn.com/b/wpfsldesigner/archive/2010/01/22/known-issue-controls-deriving-from-a-generic-base-class-must-be-in-separate-assembly.aspx).

This article mainly describes generic UserControl classes for WPF, and at the end puts the focus on the issue in Silverlight. And it gives the crucial hint: One has to create a “middle” class. The only purpose of the middle class is to create a non-generic type based on the generic base class. The declaration looks like this:

MiddleClass : GenericBaseClass<TypeClass>

where GenericBaseClass<T> itself is derived from UserControl.

The base class can be abstract. The middle class of course have to override all abstract methods. I only put a throw (new NotImpementedException("NeedsToBeOverridden")) into the implementation of these methods to remind me not to forget to override them by the derived class (the user control itself).

The user control now can be derived from the middle class, which does not require type parameters. Silverligt’s XAML parser is happy, and I am too. The declaration looks like this:

DerivedClass : MiddleClass

Simple, isn’t it?!

The reason why Silverlight requires this workaround is a lack of the x:TypeArguments property in the XAML.