Reader Level:
ARTICLE

InitParams in Silverlight

Posted by Diptimaya Patra Articles | XAML June 30, 2009
Using InitParams in Silverlight
  • 0
  • 0
  • 15644
Download Files:
 

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 tag
tag  <asp:Silverlight  add an attribute InitParameters
Enter the following code to the tag

InitParameters="Key1=Value1,Key2=Value2"

Defining the Parameters

In App.xaml.cs add an object of IDictionary<string,string> as follows

public IDictionary<string, string> AppParams;
In Application_Startup event initialize the parameters as follows
private void Application_Startup(object sender, StartupEventArgs e)
        {
            AppParams = e.InitParams;
            this.RootVisual = new Page();
        }

Using Parameters

In Page.xaml add ListBoxes to show the parameter values
Xaml Code

<UserControl x:Class="InitializingParameters.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="#FFB7C2E5">
                <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="0.472*"/>
                                <ColumnDefinition Width="0.025*"/>
                                <ColumnDefinition Width="0.502*"/>
                </Grid.ColumnDefinitions>
        <ListBox x:Name="myKeysList"/>
        <ListBox x:Name="myValuesList" Grid.Column="2"/>
    </Grid>
</UserControl>

In code behind of the Page.xaml.cs add the following code to bind the parameters

namespace InitializingParameters
{
    public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();
            App myApp = App.Current as App;

            foreach (string item in myApp.AppParams.Keys)
            {
                myKeysList.Items.Add(item);
            }
            foreach (string item1 in myApp.AppParams.Values)
            {
                myValuesList.Items.Add(item1);
            }
        }
    }
}

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.

COMMENT USING