Monday, August 9, 2010

Silverlight parameters

Scenario:
Silverlight and SharePoint 2010 is great combination. Here's a quick post of how to pass parameters to Silverlight and consume them in Silverlight.

Solution #1: (Initialization Parameters)
This is most commonly used way to pass the values. This is how we declare it.

ASPX(C#)

<asp:Silverlight ID="Xaml1" runat="server" 
Source="~/ClientBin/InitParamsMgr.xap"
MinimumVersion="2.0.31005.0" Width="100%" Height="100%"
InitParameters="param1=value1,param2=value2">
</asp:silverlight>
HTML
<object id="SilverlightPlugin1" width="300" height="300"
data="data:application/x-silverlight-2,"
type="application/x-silverlight-2" >
<param name="source" value="SilverlightApplication1.xap"/>
<param name="InitParams" value="param1=value1,param2=value2" />
<!-- Display installation image. -->
<a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50401.0"
style="text-decoration: none;">
<img src="http://go.microsoft.com/fwlink/?LinkId=161376"
alt="Get Microsoft Silverlight"
style="border-style: none"/>
</a>
</object>
How to use it in Silverlight:
1. Add the following code Application_Startup method.
private void Application_Startup(object sender, StartupEventArgs e)
{
if (e.InitParams != null)
{
foreach (var item in e.InitParams)
{
this.Resources.Add(item.Key, Uri.UnescapeDataString(item.Value)); }
}
this.RootVisual = new MainPage();
}
2. Open MainPage.xaml.cs and add the following method
private string GetParam(string p)
{
if (App.Current.Resources[p] != null)
return App.Current.Resources[p].ToString();
else return string.Empty;
}
3. Use the following code to read the parameter value
string param1value = GetParam("param1");
Solution #2: ( Query Parameters )
How to use it in Silverlight:
1. Add the following code Application_Startup method.
private void Application_Startup( object sender, StartupEventArgs e ){  
this.RootVisual = new MainPage();
string queryParam = HtmlPage.Document.QueryString["key"];
this.Resources.Add( <resourcekey>, queryParam );
}
2. Use the following code to read the parameter value
in XAML
<silverlightcontrol property={StaticResource ResourceKey} />
or in C#
object parameter = ((App)Application.Current).Resources[<Resourcekey>];

Article:
How to pass initialize parameters..

Related and Referred Articles:
MSDN
Decoding paramters

0 comments: