【先修課程】

關於本文中提到由Javascript呼叫Silverlight端程式的技巧,可以參考MSDN上的說明與教學:

【本文開始】

寫了個Silverlight 3的Mehod供Javascript呼叫,其中一個參數想設定成string[],依據文件的說明"JavaScript 陣列會轉換成 object[]"。原本預期Javascript端呼叫plugin.Content.MyManagedObject.MyMethod(["A","B"]),宣告成public void MyMethod(object[] ary)就可搞定,沒想到測試失敗,得到:

This object cannot be converted to the specified type 'System.Object[]'

研究之後,發現一個可行做法是接入ScriptObject,再利用ScriptObject.ConvertTo<string[]>轉換。測試程式碼如下:

MainPage.xaml.cs

    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            JavascriptSidekick jssk = new JavascriptSidekick();
            if (HtmlPage.IsEnabled)
                HtmlPage.RegisterScriptableObject(
                    "JavascriptSidekick", jssk);
        }
    }

JavascriptSidekick.cs

    public class JavascriptSidekick
    {
        public string[] ConvertToStringArray(ScriptObject obj)
        {
            return obj.ConvertTo<string[]>();
        }
        [ScriptableMember]
        public string Test1(ScriptObject obj)
        {
            return string.Join(",", ConvertToStringArray(obj));
        }
        [ScriptableMember]
        public string Test2(object[] ary)
        {
            return string.Join(",", 
                ary.Select(s => s.ToString()).ToArray());
        }
    }

網頁中的Script端測試:

function onSilverlightLoad(sender, args) {
    var slCtl = sender.getHost();
    var jssk = slCtl.Content.JavascriptSidekick;
    
    alert(jssk.Test1(["A","B","C"]));
    alert(jssk.Test1([]));
    
    //失敗
    //NullReferenceException
    alert(jssk.Test1(null)); 
    
    //失敗 ArgumentException
    //Invalid args for this operation.
    alert(jssk.Test1()); 
    
    //失敗 ArgumentException
    //This object cannot be converted to 
    //the specified type 'System.Object[]'
    alert(jssk.Test2(["A","B","C"]));
}        

最後,補充一篇透澈剖析Silverlight Interoperability的好文章: Silverlight interoperability


Comments

# by Phoenix

原來是這樣,之前還笨笨的先用逗號串起來傳送說@@

Post a comment