This is a mirror of official site: http://jasper-net.blogspot.com/

Interacting with javascript in Silverlight

| Sunday, November 21, 2010
ometimes you need to interact with javascript from your Silverlight application.  Sometimes you even need to have javascript manipulate the state of your Silverlight objects.  In this post I’m going to show you how you can pass an object created in Silverlight to a javascript prototype, which changes a value on that object, and then have the Silverlight application request that object back with the changed values.

Download the sample project and source for this post: Silverlight javascript Interop Demo Source

First we have a Data object.  This is a POCO object though it has one major difference – the ScriptableType attribute.  This attribute exposes all properties, methods, and events of the attributed object as scriptable endpoints.  You can selectively exclude items if you like by utilizing the ScriptableMember attribute.

[ScriptableType]
public class Data
{
   public string ID { get; set; }

   public string Status { get; set; }
}
Next we have the Application prototype in javascript.  This prototype exposes two methods, setObject and getObject.  The setObject method sets the Status of the passed in object to a specific string value.  It also holds onto the object so that other functions can have access to it.  We then also provide an app variable that can be accessed in Silverlight.

var Application = function () {
};

Application.prototype = {
   setObject: function (obj) {
       this.obj = obj;
       obj.Status = "from javascript";
   },

   getObject: function () {
       return this.obj;
   }
};

var app = new Application();

The Silverlight code is fairly straight forward.  I’m utilizing the dynamic keyword that was introduced in Silverlight 4.  This makes the code a lot cleaner and easier to read.  I’ve included some other aspects of converting dynamic javascript objects to Silverlight objects to show how the runtime is handling the objects.  In the SetData() method we’re getting the Window of the page, accessing the app instance in the window, then calling the setObject() and getObject() methods on the app prototype.

Read more: joe.mcbride

Posted via email from .NET Info

0 comments: