Combining Silverlight and JavaScript

摘要:Combining Silverlight and JavaScript

Calling Javascript Functions from Silverlight

This is the simpler of the two.  In Silverlight under the System.Windows.Browser namespace there is an object called HtmlPage.  This object gives you access to the pages DOM.  The code I use to move the square in the JavaScript area is:

HtmlPage.Window.Invoke("moveBox", newX, newY);

where "moveBox" is the name of a Javascript method I wrote to update the red square's position.

That is all I have to do!

 

Calling Silverlight Methods from Javascript

This is slightly more complicated. First in the Silverlight application I have to mark which class I want to expose to JavaScript as by giving it a Scriptable attribute:

[ScriptableType]
public partial class Page : UserControl

 

Then I need to register this class so that JavaScript can see it and give it a name for JavaScript to refer to it as:

HtmlPage.RegisterScriptableObject("silverlightMove", this);

 

Next I need to mark which methods to expose to JavaScript by giving them a  ScriptableMember attributeHere I am exposing a method called MoveBox which updates the blue square's position  in the Silverlight application:

[ScriptableMember]
public void MoveBox(int x, int y)

 

With all this setup done I can now move back to JavaScript and get ready to call the method.  To do this I need to get a reference to the pages Silverlight control:

silverLightControl = document.getElementById("silverlightControl");

Where "silverlightControl" is the id  applied to my Silverlight application object tag.

 

Once I have a reference to the Silverlight control I am able to invoke the method which I marked as a ScriptableMember using the object name I registered:

silverLightControl.content.silverlightMove.MoveBox(x, y);

I have now called MoveBox method from my C# code in the Silverlight application using Javascript!