Passing Data from HTML into Silverlight
       by kirupa  |  29 December 2008

Silverlight content often feels like an island - floating in an endless sea of HTML for as far as the eye can see. That is a common impression to have. The vast differences between Silverlight and HTML make Silverlight content seem more like an interactive image as opposed to bits of funny looking tags defined in text.

Despite the differences, there is a certain level of coexistence between HTML and Silverlight. One area where they are the best of friends is when data needs to be passed between them. In this very short article, I will show you how to pass data via HTML into a Silverlight application.

This is very useful when you want to reuse some Silverlight content across multiple pages and would like to pass in some custom values without creating a new Silverlight control nor introduce something more heavyweight like a custom XML file to store application-specific data.

Specifying the Parameters to Pass In
When you want to display a Silverlight XAP, you will use some HTML that looks similar to the following:

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

The lines to note are the tags beginning with param. To pass in your own arguments, you will need to insert your own parameter name called initParams whose value matches the following key/value format: key=value,key1=value1,...,keyN=valueN.

The example HTML incorporating my own parameters looks like the following:

<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
    <param name="source" value="ClientBin/SilverlightApplication1.xap"/>
    <param name="onerror" value="onSilverlightError" />
    <param name="background" value="white" />
    <param name="minRuntimeVersion" value="2.0.31005.0" />
    <param name="autoUpgrade" value="true" />
    <param name="initParams" value="customValue=Foo,customColor=Blue" />
    <a href="http://go.microsoft.com/fwlink/?LinkID=124807" style="text-decoration:
    none;"
>
    <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get
        Microsoft Silverlight"
style="border-style: none"/>
    </a>
</object>

I am passing in two keys (customValue and customColor) whose values are Foo and Blue respectively. Once you have specified the parameters in the HTML, the next step is to have them be recognized by Silverlight.

Modifying App.xaml.cs
Once you have your parameters specified in the HTML, you need to be able to load them into your Silverlight application. That important task falls onto App.xaml.cs. Yes, that file that you probably have been ignoring for all this time. Open App.xaml.cs and find the Application_Startup method. It should contain just one line of code setting your RootVisual to a new Page instance:

private void Application_Startup(object sender, StartupEventArgs e)
{
this.RootVisual = new Page();
}

After that line of code where your RootVisual is set, copy and paste the following lines directly below it:

if (e.InitParams != null)
{
foreach (var data in e.InitParams)
{
this.Resources.Add(data.Key, data.Value);
}
}

Your Application_Startup method will now look like the following:

private void Application_Startup(object sender, StartupEventArgs e)
{
this.RootVisual = new Page();
 
if (e.InitParams != null)
{
foreach (var data in e.InitParams)
{
this.Resources.Add(data.Key, data.Value);
}
}
}

Right now, you are probably wondering if this code can be placed somewhere else like Page.xaml.cs or something. The answer is NO. That is because the StartupEventArgs is what your InitParams are passed in through, and StartupEventArgs only exists on the Application_Startup event handler. The Application_Startup event handler only exists on classes derived from Application such as our App.xaml.cs.

You are almost done! You now have added all of your parameters into your App’s resources. The final step is to access this data.

Accessing the Resource
With your data safe inside App, retrieving it is a bit more straightforward. All you need to do is ensure the page you are wanting this data on has fully loaded (using the Loaded event) and then access the resources from App.

An example of how I did this on Page.xaml.cs can be seen below:

public Page()
{
InitializeComponent();
 
this.Loaded += new RoutedEventHandler(Page_Loaded);
}
 
void Page_Loaded(object sender, RoutedEventArgs e)
{
string color = App.Current.Resources["customColor"].ToString();
string value = App.Current.Resources["customValue"].ToString();
}

If you don’t specify this code in an event handler for the Loaded event, you may run into an error where the code in your App.xaml.cs has not fully run. This will cause your application in (this case) Page.xaml.cs to run the code for accessing your App’s resources without actually having the resource loaded. You don’t want that! By ensuring you are accessing the resources after Loaded has fired, you ensure that any resources you are looking for have indeed been loaded for you to use.


Just a final word before we wrap up. If you have a question and/or want to be part of a friendly, collaborative community of over 220k other developers like yourself, post on the forums for a quick response!

Kirupa's signature!




SUPPORTERS:

kirupa.com's fast and reliable hosting provided by Media Temple.