是否可以通过ASPX页面调用方法背后的Silverlight代码?

时间:2013-01-03 11:12:24

标签: asp.net silverlight methods silverlight-5.0

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

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

有可能吗?我该怎么做?

1 个答案:

答案 0 :(得分:2)

您可以使用Javascript进行Silverlight方法调用。

要允许用户从JavaScript访问Silverlight的方法,您必须将[ScriptableMember]属性设置为该方法。

如果要通过ASPX方法/事件调用这些方法,则应生成调用silverlight方法的Javascript。

示例:

<强> 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>