Wednesday, July 2, 2008

Adding multiple Silverlight user controls on aspx

Sometimes we have requirement of adding multiple Silverlight UserControls over same ASP.NET web page (aspx). Like when you want to host silverlight web parts on a single aspx page in separate areas.
All silverlight controls are zipped into a single .xap file. And the tag refers to xap file using source attribute as shown in the below code
<asp:Silverlight ID="Xaml1" runat="server" Source="~/ClientBin/MySLapp.xap" />
The App.xaml file contains the Application_Startup event which contains the information about the starting user control which will be rendered when the silverlight xaml is consumed by the browser. We can manipulate the InitParams property of this method to dynamically set the starting user control for the silverlight application. The below method shows how can we achieve the requirement of calling different user controls from the same aspx page.

Firstly set the different user controls on the aspx page as shown below

<asp:Silverlight ID="Xaml1" InitParameters="ControlId=1" runat="server" Source="~/ClientBin/MySLapp.xap" />
<asp:Silverlight ID="Xaml2" InitParameters="ControlId=2" runat="server" Source="~/ClientBin/MySLapp.xap" />
Next, you can dynamically set the user control to be rendered by the application using this logic
private void Application_Startup(object sender, StartupEventArgs e)
{
if (e.InitParams.ContainsKey("ControlId"))
{
if (e.InitParams["ControlId"] == "1" )
this.RootVisual = new UserControl1();
else
this.RootVisual = new UserControl2();
}
}

where UserControl1 and UserControl are you Silverlight UserControls.



2 comments:

Anonymous said...

that was exactly what i needed, thanks!

tareq said...

Thanks for this post.
I m looking this kind of article last 2 days n finally i found it.

Thanks again.