Home > Silverlight > Silverlight and javascript

Silverlight and javascript

Communication between silverlight and javascript seems to be simple

To call a Javascript function from codebehind

HtmlPage.Window.CreateInstance(“FunctionName”) ;
or
//if the function has parameters
HtmlPage.Window.CreateInstance(“FunctionName”, “param1″, “param2″) ;

to call a method in codebehind from javascript

we have to decorate the method with “ScriptableMember”

 [ScriptableMember()]
 public string GetString()
 {
     return “this is a test”;            
 }

and in App.xaml.cs, we have to register our page

 private void Application_Startup(object sender, StartupEventArgs e)
 {
     Page page = new Page();
     HtmlPage.RegisterScriptableObject(“MyPage”, page);
     this.RootVisual = page;
 }
and in the html page where the control is hosted. we can call GetString() method defined in the page

function CallCodeBehind(){      
        var retvalue = document.getElementById(“SilverlightControl”).Content.MyPage.GetString());
        }

<div id=”silverlightControlHost”>
  <object data=”data:application/x-silverlight,”
            type=”application/x-silverlight-2-b1″ width=”400″
            height=”400″ name=”SilverlightControl”/></div>

Categories: Silverlight Tags: ,
  1. kheonline
    February 18, 2009 at 7:47 am | #1

    can u convert it in vb9?

    • lee
      February 18, 2009 at 11:15 am | #2

      it should not be difficult, just copy the snippet of the code and paste it into one of the free online c# to vb converters, it will give the vb equivalent

  1. No trackbacks yet.