Monday, June 14, 2010

Silverlight & Javascript Communication (Part 2)

Call Silverlight Methods from Javascript

(http://pietschsoft.com/post/2008/06/Silverlight-and-JavaScript-Interop-Basics.aspx)

Setup your Silverlight object as Scriptable

[ScriptableType]
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
this.Loaded += new System.Windows.RoutedEventHandler(Page_Loaded);
}

void Page_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
// Register this object in the page as Scriptable
// so it can be access from within JavaScript
HtmlPage.RegisterScriptableObject("Page", this);
}

[ScriptableMember]
public double GetDoubleValue()
{
// return a double
return (double)42;
}
}

Write your Javascript code

<script type="text/javascript">
function callGetDoubleValue()
{
var sl = window.document.getElementById('mySilverlightObject');

// Call the GetDoubleValue method of our Silverlight object
// notice we are referencing the object by the name of "Page", that we setup
// in Silverlight when we registered the object as Scriptable
var dbl = sl.content.Page.GetDoubleValue();

// Display the value to the user in an alert box
alert(dbl);
}
</script>


mySilverlightObject refers to the object Id of the Silverlight object in HTML code.

e.g.
<div id="SilverlightControlHost"><object id='
mySilverlightObject' …>…</object></div>

Return objects from Silverlight method calls to Javascript

The objects need to be marked as Scriptable, and the members you want to expose must be marked with the ScriptableMember attribute.

[ScriptableMember]
public myObject GetObjectValue()
{
myObject o = new myObject();
o.Name = "Chris";
return o;
}

[ScriptableType]
public class myObject
{
[ScriptableMember]
public string Name { get; set; }

[ScriptableMember]
public string GetName()
{
return this.Name;
}
}

To access the returned objects in Javascript:

// Call the method and get the returned object
var obj = plugin.Content.myObject.GetObjectValue();

// Get the value of a property of the retured object
var strName = obj.Name;

// Get the returned value of a method of the returned object
var strName = obj.GetName();


Related:

Call Javascript methods from Silverlight
Handling ScriptObjects


No comments:

Post a Comment