Friday, November 20, 2009

Silverlight: Specify Control To Load Via Launch Parameter

Shortly after integrating a Silverlight control into my application, I discovered that I would want to be able to run more than one control from the same Silverlight application.  My framework that I developed consisted of the following:
  1. A javascript function to launch the Silverlight control.
  2. A modification of the App class in my Silverlight application.
The first thing I had to do was modify the javascript that launched the Silverlight application.  I had to include a param to the <object> control.  The name of the param is “InitParams”.  This is the value that gets passed to the Silverlight App class (this is a Silverlight parameter and you seperate multiple parameters with the ',').  I simply set it to a value that contains “Page=MyControlClassToLaunch”.

"<param name='InitParams' 
value='Page=Namespace.ControlClass' />";

After changing the <object> tag to have a parameter specifying the control I wanted to load, I needed to modify the App class to make sure that it loaded the control.

To do this, I had to override the Startup event.  In that method, I check the InitParams to get the Page param out of it.  Once I had the Page to load, I had to use reflection to get all the types from the Silverlight assembly.  I then iterate over all the types to find the type that matches the type passed in the Page param.

Once we have the Type of the control to load, we use the Activator.CreateInstance method to instantiate the control.

Now that we have the control instantiated, all we need to do is set the RootVisual property of the App class and we have successfully used an <object> tag param to tell the App which control we would like to launch.
 
private void Application_Startup(object sender, 
StartupEventArgs e) {
  if (e.InitParams.ContainsKey("Page")) {
      string page = e.InitParams["Page"];
      Type[] types = Assembly.GetExecutingAssembly().GetTypes();
      foreach (Type type in types) {
          if (type.FullName == page) {
              RootVisual = 
(UIElement) Activator.CreateInstance(type);
              return;
          }
      }
  }
  RootVisual = new DefaultPage();
}

It is now possible to have many Silverlight controls all located within a single application and launch different ones from javascript by easily setting a parameter on the tag.