How to pass parameters to Silverlight controls from ASP.NET pages ?

0 comments
You can pass parameters from your aspx pages and html pages to the Silverlight controls. This chapter explains how to pass parameters to Silverlight controls from your aspx page and code behind files.

InitParameters

The Xaml page user control has a property called InitParameters. You can set a value in the form of key-value pairs from your ASPX pages. Since this property accepts key-value pairs, you can pass any set of string values.

How to set InitParameters

Example - Set InitParameters property from ASPX page:

<asp:Silverlight
   ID="Xaml1"
runat="server"
   Source="~/ClientBin/MySilverlightApp.xap"
   InitParameters="City=Houston,State=Texas,Country=USA"
   Width="300"
   Height="300" />

You can set this property from the code behind file of your ASPX page as well.

Example - Set InitParameters property from the code behind file:

Xaml1.InitParameters = "City=Houston,State=Texas,Country=USA";

How to retrieve the InitParameters value ?

The value you pass to a Silverlight control through the InitParameters property can be retrieved from the Application_Startup even handler in the App.xaml page.

private void Application_Startup(object sender, StartupEventArgs e)
{
    IDictionary parameters = e.InitParams;

    this.RootVisual = new Page1();

Now, in most cases, you may want to pass this value to the xaml page itself instead of doing anything with in it the App.xaml.

Pass parameters from App.xaml to other pages

To pass the parameters from the App.xaml pages to other pages, you must modify the constructor of xaml page class to accept parameters.

private IDictionary<string, string> parameters = null;

public Page1()
{
    InitializeComponent();
}

public Page1(IDictionary<string, string> p)
{
    this.parameters = p;

    InitializeComponent();
}
 The above sample shows an additional constructor added which takes a parameter of type IDictionary and then sets the value to a member variable.

Now go back to your App.xaml and pass the parameters to the page:

private void Application_Startup(object sender, StartupEventArgs e)
{
    IDictionary parameters = e.InitParams;
    this.RootVisual = new Page1(parameters);


0 comments: