现在的位置: 首页 > 综合 > 正文

Script and managed code in Silverlight

2012年04月23日 ⁄ 综合 ⁄ 共 2517字 ⁄ 字号 评论关闭
All Cases

  • JS invoke managed code in Silverlight
  • Managed code in Silverlight invoke JS
  • JS invoke managed code out of Silverlight --XMLHttpRequest, post back event, hidden button
  • Managed code out of Silverlight invoke Js --RegisterStartupScript

1, JS invoke managed code in Silverlight

 

Description: Need to invoke function or property in managed code which is placed in Silverlight project

Managed method in Silverlight:

public class Scriptable
{
    [ScriptableMember()]
    public string ManagedCodeToUpper(string str)
    {
        return str.ToUpper();
    }
    [ScriptableMember()]
    public string ManagedCodeProperty { get; set; }
}

Then in App.xaml.cs, you should modify Application_Startup, register the class instance to script

private void Application_Startup(object sender, StartupEventArgs e)
{
    this.RootVisual = new Page();
    HtmlDocument doc = HtmlPage.Document;
    //Enable the html textbox on the page and change the value
    doc.GetElementById("Text1").SetProperty("disabled", false);
    doc.GetElementById("Text1").SetAttribute("value", "Set from managed code");
    //set up scriptable managed types for access from javascript
    Scriptable scriptable = new Scriptable();
    HtmlPage.RegisterScriptableObject("scriptKey", scriptable);
    //HtmlPage.RegisterScriptableObject("scriptKeyStatic", Scriptable.ManagedCodeProperty);
    //HtmlPage.RegisterCreateableType("scriptCreateableType", typeof(Scriptable));
}

As above we also can change the property or attribute here with HTMLDocument(System.Windows.Browser)
And register the instance of class Scriptable to JS
After all of these, we can invoke these managed methods with JS

Don't forget to add the line below:

<param name="onLoad" value="pluginLoaded" />

2, Managed code in Silverlight invoke JS

Description: Need to invoke a Js function from managed code and with the js function change DOM's value

The below JS function is to be invoked from sl managed code

Use HTMLDocument to attach an event to this button

private void Application_Startup(object sender, StartupEventArgs e)
{
    this.RootVisual = new Page();
    doc.GetElementById("button2").AttachEvent("click", new EventHandler(scriptable.CallGlobalJSMethod));
}

The event handler is as follow

public void CallGlobalJSMethod(object sender, EventArgs e)
{
    HtmlPage.Window.Invoke("JSFunction",
                                         "public string ManagedCodeToUpper(string str)",
                                        "{",
                                                " return str.ToUpper();",
                                        "}");
}

 

抱歉!评论已关闭.