May 17

Well, sort of. To be able to do this, there are some prerequisites:

  • The Canvas type must be annotated with the ScriptableAttribute;
  • You must expose an event which the js code on the page should handle;
  • You must register your control with the WebApplication object by calling the RegisterScriptableObject method.

Here”s a quick example (just the important parts):

public partial class Demo: Canvas{

   public void Page_Loaded( object o, EventArgs e ){
       //register this object so that it”s accessible from JS
       WebApplication.Current.RegisterScriptableObject( “Managed”, this );

   public event EventHandler SomethingHappened;

   //more code


Now, on your html page, you can handle the Load event of the Silverlight control so that you can hook up the SomethingHappened event with a custom js method:

function handleLoad( sender, e ){
   sender.Content.Managed.SomethingHappened = myMethod; //myMethod is a js function

function myMethod( sender, e ){

And that”s it (i didn”t show the code for firing the event because it”s just like you do in traditionat .NET programming).

Notice how the name used during the registration is “added” by the Silverlight  control to the Content property, letting you access all the ScriptableAttribute annotated elements from js code…

Btw, do note that besides events, you can also expose other elements from your Silverlight types (which I”ll talk in a future post). Still regarding the events,you can also use a custom EventArgs type and it”ll get passed to the js method. When you do this,you should also annotate your custom EventArgs class with the ScriptableAttribute and make sure that all the elements that you want to use from js are of type int, double, string or ScriptableObject (complex types should be serialized into JSON and passed as strings). If you don”t follow these rules, you”ll get an exception during the RegisterScriptableObject method call.

5 comments so far

  1. Hristo Deshev
    6:23 am - 5-18-2007

    sender.Content.Managed.SomethingHappened = myMethod;

    The above code makes me think that the event handling does not do multicasting. Can we have several event handlers attached there?

    Hristo Deshev

  2. Luis Abreu
    8:53 am - 5-18-2007

    yeah, i believe that in this version you can only hook up one method.

  3. bor!s
    5:37 am - 9-26-2007

    Is it possible to pass parameters to the js function from managed code and get any returns?

    I”m trying to get/set some cookies from my silverlight app – but have not figured out a way to do this as of yet…

  4. Chipl
    11:22 am - 12-25-2007

    The command on JS such as :
    onload: onLoaded
    // to hook up a function

    my JavaScript engine alway throw out a message like:
    “c.charCodeAt is not a function”
    How do I solve it ???


  5. jhlee
    7:28 am - 1-2-2008


    onload: onLoaded -> onLoad: onLoaded

    notice ”l” and ”L”. ^^;