In a Silverlight 3 application there is by default a limitation to Page and UserControl inheritance. As ASP.net developers we are used to creating BaseControls from which multiple other controls can inherit common functionality. This of course gives us the ability to control/reduce the amount of functionality/code duplication that takes place in our application which also results in making our applications more readable and maintainable.
In order to work around this limitation I have spent hours writing and re-writing code trying to get the inheritance to work as it should within a Silverlight 3 application with no luck. It wasn’t until I saw the ‘Silverlight Class Library’ project and decided that it would be a good idea to move my controls to a separate assembly for reuse in other projects. It was while I was investigating Silverlight class libraries online that I found out we have the ability to not only use the control library to separate out our controls for reuse but we also have the ability to add to the control libraries assembly info definitions for our own Silverlight XML Namespace definitions for the controls we create in the library.
What does this mean to us when it comes to inheritance? It allows us to define our own base classes within the library which inherit from both system provided base classes Page and UserControl. Then once we add the XML Namespace to the assembly info file we can then use any of those base classes as the base classes for all other controls we create inside the library or inside our Silverlight 3 application which references the library instead of using the system defaults. This of course allows us to place common functionality within these base classes which will then be inherited by all of our derived controls/pages.
To accomplish this you first create a ‘Silverlight Class Library’ project and add to it a new ‘Class’ file (NOT a UserControl or Page) then specify that this new class derives from either ‘UserControl’ or ‘Page’.
Once you have create the class you then have to do the most important step of all, this is what allows you to use the base class for inheritance. You need to add to the AssemblyInfo.cs file the following line of course updating the Namespace portion (the second string) to the namespace where your base page lives within the assembly.
Once you have done this you can build the assembly reference it in your project and from that point each time you add a UserControl or a Page to your Silverlight 3 project you can then modify it to use your custom base classes and now you have inheritance!