InitParams in Silverlight

Introduction

If you are developing a Silverlight Application, and you need to pass some parameters inside – for example a key and value pair then we can pass the key value pair from the aspx page itself. We will see how we can do this in Silverlight.

Create a Silverlight Project

image1.gif

Figure 1.1 Creating Silverlight Project

Adding parameters

Open the "InitializingParametersTestPage.aspx" and find the tagtag <asp:Silverlight add an attribute InitParameters

Enter the following code to the tag
  1. InitParameters="Key1=Value1,Key2=Value2"  
Defining the Parameters

In App.xaml.cs add an object of IDictionary<string,string> as follows
  1. public IDictionary<stringstring> AppParams;  
  2. In Application_Startup event initialize the parameters as follows  
  3. private void Application_Startup(object sender, StartupEventArgs e)  
  4. {  
  5.     AppParams = e.InitParams;  
  6.     this.RootVisual = new Page();  
  7. }  
Using Parameters

In Page.xaml add ListBoxes to show the parameter values

Xaml Code
  1. <UserControl x:Class="InitializingParameters.Page"  
  2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"   
  3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"   
  4.     Width="400" Height="300">  
  5.     <Grid x:Name="LayoutRoot" Background="#FFB7C2E5">  
  6.                 <Grid.ColumnDefinitions>  
  7.                                 <ColumnDefinition Width="0.472*"/>  
  8.                                 <ColumnDefinition Width="0.025*"/>  
  9.                                 <ColumnDefinition Width="0.502*"/>  
  10.                 </Grid.ColumnDefinitions>  
  11.         <ListBox x:Name="myKeysList"/>  
  12.         <ListBox x:Name="myValuesList" Grid.Column="2"/>  
  13.     </Grid>  
  14. </UserControl>  
In code behind of the Page.xaml.cs add the following code to bind the parameters
  1. namespace InitializingParameters  
  2. {  
  3.     public partial class Page : UserControl  
  4.     {  
  5.         public Page()  
  6.         {  
  7.             InitializeComponent();  
  8.             App myApp = App.Current as App;  
  9.             foreach (string item in myApp.AppParams.Keys)  
  10.             {  
  11.                 myKeysList.Items.Add(item);  
  12.             }  
  13.             foreach (string item1 in myApp.AppParams.Values)  
  14.             {  
  15.                 myValuesList.Items.Add(item1);  
  16.             }  
  17.         }  
  18.     }  
  19. }  
Runnning the Application

When you run the application the list will carry the key and value pairs.

image2.gif

Figure 1.2 Displaying Key Value pair

Hope you like the article, Enjoy Coding.


Recommended Free Ebook
Similar Articles