2

我在我的 ASP.NET 页面中嵌入了一个 Silverlight 应用程序,这个 Silverlight 应用程序有两种方法。

我想通过 ASPX 页面调用这些方法,即我的 ASPX 页面有一个Button控件,当我单击此按钮时,我想调用 Silverlight 方法之一。

可能吗?我该怎么做?

4

1 回答 1

3

You can use Javascript to make a silverlight method calls.

To permit user to access method of Silverlight from JavaScript, you have to set [ScriptableMember] attribute to that method.

If you want to invoke those methods by ASPX methods/events, you should generate Javascript that invokes the silverlight methods.

Example:

Silverlight:

ScriptableClass.cs

public class ScriptableClass
    {
        [ScriptableMember]
        public void ShowAlertPopup(string message)
        {
            MessageBox.Show(message, "JS Message", MessageBoxButton.OK);
        }
    } 

App.xaml.cs

 private void Application_Startup(object sender, StartupEventArgs e)
        {
            this.RootVisual = new MainPage();
            ScriptableClass myScript = new ScriptableClass();
            HtmlPage.RegisterScriptableObject("scriptableClass", myScript);
        } 

index.html

 <script type="text/javascript">     
        var ctlSLHost = null;
        function onPluginLoaded(sender, args) {
            ctlSLHost = sender.getHost();
        }

        function InvokeSLMethod_ShowAlertPopup() {
            ctlSLHost.Content.scriptableClass.ShowAlertPopup
        ("Showing alert from JS in SL!");
        } 
    </script>

<div>
        <div style="width: 250px; background: lightblue; font-weight: bold;height:30px">
            HTML Part
        </div>
        <div>
            <input type="button" value="Invoke SL Method - ShowAlertPopup" 
        onclick="InvokeSLMethod_ShowAlertPopup();" /></div>
    </div>

 <object data="data:application/x-silverlight-2," type="application/x-silverlight-2"
            width="100%" height="80%">
            <param name="source" value="ClientBin/Silverlight2JSViseVersa.xap" />
            <param name="onError" value="onSilverlightError" />
            <param name="background" value="white" />
            <param name="minRuntimeVersion" value="4.0.50826.0" />
            <param name="autoUpgrade" value="true" />         
            <param name="onLoad" value="onPluginLoaded" />

            <a href=http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50826.0 
        style="text-decoration: none">
                <img src=http://go.microsoft.com/fwlink/?LinkId=161376 
        alt="Get Microsoft Silverlight"
                    style="border-style: none" />
            </a>
        </object> 
于 2013-01-04T21:03:44.787 回答