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.

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

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


[Personalizable(PersonalizationScope.Shared),
WebBrowsable(true),
WebDisplayName("Name"),
WebDescription("The person who is being greeted."),
Category("Configuration")]
public string Name
{
get { return name; }
set { name = value; }
}


STEP TWO:
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.

STEP THREE:
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"];

STEP FOUR:
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();
this.name = 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: