Provide startup parameters to Silverlight with InitParams

I have been giving Silverlight trainings for a while now, and I found this to be a little known feature: the ability to provide Silverlight startup parameters with InitParams.

 

Pass startup parameters to your Silverlight app

You pass the parameters as a key/value pair collection in the initParams param of the object tag. (For a comprehensive list of param you can set, see my previous post).

<object data="data:application/x-silverlight," type="application/x-silverlight-2" width="100%" height="100%">
    <param name="source" value="ClientBin/InitParamsSample.xap"/>
    <param name="onerror" value="onSilverlightError" />
    <param name="background" value="white" />
    <param name="initParams" value="module=news,nb=10" />
    <a href="http://go.microsoft.com/fwlink/?LinkID=115261" style="text-decoration: none;">
        <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none"/>
    </a>
</object>

 

Get the parameters in Silverlight

You get the startup parameters in the Application_Startup() event handler of the App class:

App.xaml.cs

private void Application_Startup(object sender, StartupEventArgs e)
{
    foreach (var item in e.InitParams)
    {
        this.Resources.Add(item.Key, item.Value);
    }

    this.RootVisual = new MainPage();
}

If you store them as Resources, then you can use them in any page like that:

MainPage.xaml.cs

public partial class MainPage : UserControl
{
    string module = string.Empty;
    int nb = 0;

    public MainPage()
    {
        InitializeComponent();

        this.Loaded += new RoutedEventHandler(MainPage_Loaded);
    }

    void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        if (App.Current.Resources.Contains("module"))
        {
            module = App.Current.Resources["module"].ToString();
        }
        if (App.Current.Resources.Contains("nb"))
        {
            int.TryParse(App.Current.Resources["nb"].ToString(), out nb);
        }

        // Display the nb latest items from the selected module...
    }
}

 

Alternative option

Or even better with a constructor in your xaml page:

App.xaml.cs

private void Application_Startup(object sender, StartupEventArgs e)
{
    if (e.InitParams.Keys.Contains("module"))
    {
        module = e.InitParams.Keys["module"].ToString();
    }
    if (e.InitParams.Keys.Contains("nb"))
    {
        int.TryParse(e.InitParams.Keys["nb"].ToString(), out nb);
    }

    this.RootVisual = new MainPage(module, nb);
}

 

MainPage.xaml.cs

public partial class MainPage : UserControl
{
    public MainPage(string initModule, int initNb)
    {
        InitializeComponent();

        // Display the nb latest items from the selected module...
    }
}


Download Sample project

 

Technorati Tags:

No Comments