Passing Parameters Into Silverlight Applications

I was working on a chapter about the Application Model for our forthcoming book and reviewed the examples on passing parameters into Silverlight applications. I thought, "Hey! That would make a great video!"  And it does, but Tim already made one, which I highly recommend.

Since it never hurts to review, I’m going to write this up quickly, fully acknowledging that this is 90% his work; so only read on if you haven’t happened to catch his presentation of this material yet and this might be new to you (I have added a few new bits that I learned as I worked this through).

What You’re Trying To Accomplish

The idea is this: you want to be able to create a Silverlight application that allows for passing in some information through the html or aspx page that will be integrated into the Silverlight application at run time. Remembering that Silverlight runs on the client, that information must be picked up just as the application begins to run inside its hosting html or aspx page. Here, briefly, is how you can do that:

If you are hosting in an HTML page, you’ll add a new parameter to the object tag 

ObjectTag

You’ll find there are already a number of parameters there, you’ll add one whose name is initParams and whose value is any number of name/value pairs that you’d like to pass as parameters to your program. For example,

<object data="data:application/x-silverlight-2," 
   type="application/x-silverlight-2" 
   width="100%" height="100%">
       <param 
       name="initParams" 
       value="programmer=Jesse Liberty,
       blog=http://silverlight.net/blogs/jesseliberty" />

The name/value pairs are comma separated and you may have as many as you like,

<object data="data:application/x-silverlight-2," 
   type="application/x-silverlight-2" 
   width="100%" height="100%">
      <param 
      name="initParams" 
      value="programmer=Jesse Liberty,
      blog=http://silverlight.net/blogs/jesseliberty",
      title=silverlight geek,
      codeRippedOffFrom=tim heuer,
      conceptDemonstrated=initializing parameters />

 

In this second example, I’m passing in five initializing parameters. The keys are

  • programmer
  • blog
  • title
  • codeRippedOffFrom
  • conceptDemonstrated

and their respective values are

You can see that this lends itself readily to being placed in a dictionary, and that is exactly what will happen, they are placed into an IDictionary<string><string> available to you from the Application_Startup method in App.xaml.cs (but only there, and thus only when your application is starting up).  You therefore want to grab these values and put them somewhere you can get to them later, when you’ll need them.

Stashing Away The Values

The canonical solution is to place them into the global resources dictionary, thus

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

 

Using the parameters

Once the parameters are safely tucked away we can think about using them in the running program.  I wrote a small example program that has a TextBlock for a title, a ListBox to display some data and then two rows that display information if that information is passed in through parameters.

The first row will display the programmer’s name if there is a parameter whose key is programmer, and the second will provide a link to the programmer’s blog if there is a parameter whose key is blog.   Here is the Xaml that sets that up:

<TextBlock
  x:Name="Programmer"
  Grid.Row="1" Grid.Column="1"
  FontSize="14"
  Margin="10,0,0,0" />
<HyperlinkButton
  x:Name="BlogLink"
  Grid.Row="2" Grid.Column="1"
  FontSize="14"
  Margin="10,0,0,0" />
<TextBlock
  x:Name="BlogText"
  Grid.Row="2"
  Grid.Column="1"
  FontSize="14"
  Margin="10,0,0,0" />

Notice that both the HyperlinkButton and the TextBlock occupy the same row and column. The first thing we do in the load handler is to make them both invisible,

 void Page_Loaded( object sender, RoutedEventArgs e )
 {
   BlogText.Visibility = Visibility.Collapsed;
   BlogLink.Visibility = Visibility.Collapsed;

We’ll check the resources for the link and if we find one, we’ll make the link visible; if not, we make the textblock visible and put a message there that there is no link.

Retrieving Values from the Resources Collection

Following Tim’s approach, I’ve factored out the job of getting the value out of the Resources given a key, checking first to ensure that the key exists in the resources collection and returning an empty string otherwise,

private string GetParam( string p )
{
  if ( App.Current.Resources[p] != null )
    return App.Current.Resources[p].ToString();
  else
    return string.Empty;
}
Note: You might expect to use the TryGetValue method on the Resources collection, which does exactly this work for you, but the Silverlight documentation notes that this is not intended for use in user code with the ResourcesDictionary class.

With our GetParam method in place, we can try to get the value for the Programmer and the address for the blog, placing them in local (temporary) variables,

void Page_Loaded( object sender, RoutedEventArgs e )
{
  BlogText.Visibility = Visibility.Collapsed;
  BlogLink.Visibility = Visibility.Collapsed;

  string programmer = GetParam( "programmer" );
  string blog = GetParam( "blog" );

  if ( programmer.Length > 0 )
    Programmer.Text = "Programmer: " + programmer;
  else
    Programmer.Text = "Programmer unknown";

The next step is to test whether we received a legitimate blog address. If so, we want to make the HyperTextButton visible and set its text and its URI, otherwise we’ll make the TextBlock visible and set its text to some sort of error message,

if ( blog.Length > 0 )
{
  BlogLink.Content = "Programmer's Blog";
  BlogLink.NavigateUri = new System.Uri( blog );
  BlogLink.Visibility = Visibility.Visible;
}
else
{
  BlogText.Text = "No blog provided";
  BlogText.Visibility = Visibility.Visible;
}

The result is very gratifying, the parameters are integrated into the running Silverlight program seamlessly,

ParametersCompleted

A very nice, and easily overlooked feature. Again, for complete coverage, I recommend Tim’s video and the complete source code for the example shown today is available here.

Share

About Jesse Liberty

Jesse Liberty is a Master Consultant for Falafel Software, and has three decades of experience writing and delivering software projects. He is the author of 2 dozen books and multiple Pluralsight courses, and has been a Technical Evangelist for Telerik and for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS.
This entry was posted in z Silverlight Archives. Bookmark the permalink.

11 Responses to Passing Parameters Into Silverlight Applications

  1. Pingback: Is it possible to obtain a reference to a silverlight’s page from a WebPart? | Yoon Answers

  2. ahmed elashry says:

    only by you instruction i managed to start each SilverLightPage by different AspPages
    I used the parameter and changed the default silverlight page based on the calling aspPage

    Thank you very much

  3. Hello, I believe your site could possibly be having browser compatibility issues.

    Whenever I take a look at your site in Safari, it looks fine however, when opening
    in I.E., it has some overlapping issues. I simply wanted to
    give you a quick heads up! Aside from that, excellent blog!

  4. Chris Freiling says:

    Wow!
    You’re a genious!
    Thanks so much!

  5. Will says:

    This article was super helpful! Thanks Jesse.

  6. Karthik Jeya kumar says:

    really very nice article

  7. pouya says:

    Hi
    very useful article thank you a lot my friend
    Now i have problem
    let say i have 2 silverlight page page1.xamel(my startup page that has shown in the silverlight object in html page ) and page2.xamel
    and also i have a HTML button
    how can i navigate from page1.xamel to page 2.xamel within that silverlight obejct by pressing my html button??

  8. Cahya Darma says:

    I’m sorry I think the code parsed not correctly in comment. This is my initParams:
    param name=”initParams” value=”Name=MyCollege, Latitude=-7.593545, Longitude=111.892801″

  9. Cahya Darma says:

    Hello mr. Jesse. I’m playing with Silverlight Bing Maps Control and passing params to the control like this:

    Using your technique I’m able to catch the values. However, the Latitude & Longitude values need to be convert to double type so they fit to the Location instance. But too bad the conversion doesn’t preserve the format (-7.593545 becomes -7593545 and 111.892801 becomes 111892801) so the map will direct to wrong places. Any helps to solve this?

    Thank you so very much. Regards.

    • If the entire thing is passed as a string you should be able to parse out the number part using string operators, and then convert to double using the convert operator.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>