Friday, June 18, 2010

Returning a string array to Javascript from Sliverlight

This took a lot of trial and error, but I finally figured out how to return to Javascript a string array. There where many different examples out on the web to call Javascript, passing a string array. But, no examples had Javascript calling a Silverlight function with a string array as the return value.

I first tried the direct approach:

javascript:
function TalkToSilverlight(data) {
var control = document.getElementById("silverlightControl");
var myStringArray = control.Content.Page.ReturningStringArray();
alert('length = ' + myStringArray.length + " : Value of First Element = " + myStringArray[0]);
}


Silverlight C#
public App()
{
HtmlPage.RegisterScriptableObject("Page", this);
//The rest I've elided
}

[ScriptableMember]
public string[] ReturningStringArray()
{
return new [] { "e", "i", "e", "i", "o" };
}


Well to make a long story short, a small little mention of the IList interface on MSDN was the key, all I "needed" to do (as opposed to all the changes I tried) was change the return value from string[] to IList.

No comments: