Sunday, October 07, 2007 8:39 PM
sporter
The Silverlight 1.1 Control Base Class You Should Be Using
There are a couple things that I think a Silverlight control base class should be doing for you. First of all it should load up the appropriate XAML from the resource collection for you. As long as you follow the naming and association convention of Namespace.ClassName.xaml this is fairly easy to do. With just a little bit of reflection code you can get the namespace and class names to build the filename from. This will end up saving you some debug cycles when you copy/paste a control to create a new control forgetting to update the string referencing the XAML file for the new control.
|
string xamlFileName = string.Format("{0}.{1}.xaml" , this.GetType().Namespace , this.GetType().Name);
|
The second thing your base class should be doing for you is storing a reference to your top level Canvas object. You will then use this reference to find existing child objects such as StoryBoards, TextBlocks, or MediaElements or maybe add new controls/objects to the children collection. Whatever logic you are writing in your control, you are guaranteed to need a reference to this root object.
|
RootCanvas = (Canvas)this.InitializeFromXaml(new System.IO.StreamReader(s).ReadToEnd());
|
Hopefully this will help out. Below is the complete source for the base class.
|
public class CustomControlBase : Control { private Canvas _rootCanvas; protected Canvas RootCanvas { get { return _rootCanvas; } set { _rootCanvas = value; } }
public CustomControlBase() { System.IO.Stream s = LoadXamlStream(); RootCanvas = (Canvas)this.InitializeFromXaml(new System.IO.StreamReader(s).ReadToEnd()); }
protected System.IO.Stream LoadXamlStream() { string xamlFileName = string.Format("{0}.{1}.xaml" , this.GetType().Namespace , this.GetType().Name); return this.GetType().Assembly.GetManifestResourceStream(xamlFileName); } }
|