Sunday, September 13, 2009

SilverLight – Interacting with the DOM and JavaScript

1. Updating a DOM element from Silverlight:

HtmlPage.Document.GetElementById("divStatus").SetProperty("innerHTML", "<b>loaded</b>");
The above code updates a div in the page called divStatus with the text loaded. 2. Calling a JavaScript function from Silverlight:
HtmlPage.Window.CreateInstance("testFunction", new string[] { "loading done" });
The above code calls a method called testFunction with the parameters “loading done”. The javascript function is defined as follows in the page:
<script type="text/javascript">
  function testFunction(s)
  {
      document.getElementById("divStatus").innerHTML = s;
  }
</script>

3. Calling a method in the SilverLight class

In the XAML code behind, in the constructor, you need to add the following code:

HtmlPage.RegisterScriptableObject("svMainPageObj", this);
Here, “svMainPageObj”, is the key which will be used to access the SilverLight object’s method from JavaScript.
Add the following code to the class, which will be called from JavaScript.
[ScriptableMember]
public void TestMethod(string value)
{
   string v = value;
}
Now, in the aspx page, add the following code to call the TestMethod method in SilverLight:
var obj = document.getElementById("veMapObj").content.svMainPage;
obj.TestMethod("hello");
Also make sure that the silverlight object has an ID defined (done as follows) – which is used to reference the SilverLight object in the javascript method:
<object id="veMapObj" data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%"&gt

4. Passing initialization parameters to the SilverLight object

Sometimes, you need to pass initialization parameters to the SilverLight object. The object definition in the HTML page, provides initparams as a mechanisim to do this (in the object definition of the SilverLight object in the aspx page) add the following:

<param name="initparams" value="val1=silverlight,val2=asp.net" />
In the code behind page for App.xaml (app.xaml.cs) update the Application_Startup method with the following code:
private void Application_Startup(object sender, StartupEventArgs e)
{
  var o1 = e.InitParams["val1"];
  var o2 = e.InitParams["val2"];
  this.RootVisual = new MainPage(o1,o2);
}
notes:
you need to use the following namespace - System.Windows.Browser;
the above code worked with SilverLight 3 (3.0.40624.0)

No comments: