Thursday, March 8, 2012

Accessing Instance Properties in Silverlight from JavaScript

I have been messing around with the HTML bridge between Silverlight and JavaScript recently and have a few different posts on this topic that may help others. While those doing Silverlight are starting to see "the writing on the walls" as they say and may become the next technology to 'retire' akin to ActiveX controls from the IE4 days, it is still quite prominent as of this post so topics and discussion on it are well worthwhile.

There are several posts about exposing methods and properties to JavaScript from Silverlight so I will not get into that here. However most of the examples are really 'vanilla' as usual and don't offer more than the basic information.

One thing I wanted to do was access an instance property in Silverlight from JavaScript. There really is no major trick to it and it is as straight forward to access as it should be... for once.

So let's begin by looking at the exposed properties on the Silverlight control below. There is a simple 'String' and then an instance property of 'MyCustomClass' which is the focus of this post. Let's assume 'MyCustomClass' has (2) simple String properties on it: 'Name' and 'Address'.
<ScriptableMember()>
Public Property Description As String

<ScriptableMember()>
Private _MyClass1 As New MyCustomClass
Public Property MyClass1() As MyCustomClass
Get
Return _MyClass1
End Get
Set(ByVal value As MyCustomClass)
_MyClass1= value
End Set
End Property
Next we need to register our class to be accessible by script as well which is shown below. This can be done in the constructor of the control. 'Me' (or 'this' for C#) is my Silverlight control class instance behind the .xaml control.

HtmlPage.RegisterScriptableObject("MySLControl", Me)
Now you *might* think you need to register another member above for the instance property, but you do not need to do that. You can drill down to it through the main class instance exposed as a scriptable member as shown below:
//Get instance of the Silverlight File Upload Control
var SLControl = document.getElementById("SilverlightControl");
if (SLControl != null)
SLControl.Content.MySLControl.Description = "Blah";
//Drill down through the instance property exposed on the Silverlight control
SLControl.Content.MySLControl.MyClass1.Name = "Allen Conway";
SLControl.Content.MySLControl.MyClass1.Address = "123 Oak Street";
One thing to take note of - notice how I used a long hand property for 'MyClass1' rather than an AutoProperty. If you use an AutoProperty and can't provide an object that has been instantiated for its backing value by default or when setting its value, the JavaScript block will throw an error stating "Object reference not set to an instance of an object" when accessing the MyClass1 instance properties.

That's all there is to it. You can just drill down to the instance property through the registered instance of the scriptable type.

No comments:

Post a Comment