Wednesday, April 16, 2008

Passing Arguments to Silverlight Web Parts

Here's how you can pass values to Silverlight applications embedded inside of a (SharePoint) web part.

As an example, consider the HelloSilverlight example from the recently posted Silverlight for SharePoint Blueprints. We want to allow users configuring the web part to specifiy who is being greeted.

Create a browsable public property inside of the HelloSilverlight2 web part (HelloSilverlight2.cs).

private string name = "Gaylord"; // default value

WebDescription("The person who is being greeted."),
public string Name
get { return name; }
set { name = value; }

Set the InitParameters property of your instance of
System.Web.UI.SilverlightControls.Silverlight. Specifically, add the following line of code to HelloSilverlight2.CreateChildControls().

silverlightControl.InitParameters =
string.Format("Name={0}", Name);

Note: if you have multiple parameter to pass, separate each key/value pair with a comma.

Go now to method Application_Startup() of your Silverlight application (App.xaml.cs). Extract the Name parameter from the StartupEventArgs instance passed as an argument to Application_Startup().

string name = e.InitParams["Name"];

For the HelloSilverlight2 app, we want to pass in the value for Name to the instance of Page. Therefore, we'll create a new contructor for Page

private string name;
private string displayText;

public Page(string name)
InitializeComponent(); = name;
displayText = string.Format("Hello {0}!", name);
HelloWorldTextBlock.Text = displayText;

and invoke the new constructor (instead of the old parameterless constructor) inside of Application_Startup().

this.RootVisual = new Page(name);

For completeness sake, you'll want to modify TextBlock_MouseLeftButtonUp() to use the value of displayText.

No comments: