----------http://dotnet.aspx.cc/article/4c011275-509f-4cce-8274-258477ce5f77/read.aspx
在上一篇文章中,講述了JavaScript與Silverlight託管代碼相互調用的一些方法。實際上,HtmlWindow的GetProperty方法和Invoke/InvokeSelf方法的返回值是Object類型的,代表 DOM對象或者JavaScript對象(HtmlDocument、HtmlElement、HtmlObject、ScriptObject)的返回值自動作爲最接近的類型進行返回,但是,程序開發人員仍然需要明確地將該對象轉換成相應的類型。所有的數字,由於跨瀏覽器的原因,都作爲Double類型返回,如果需要Int32類型,則執行Convert.ToInt32()方法即可。 在現代的Web應用中,JSON的使用越來越頻繁。Silverlight 2中要調用JavaScript中的JSON對象,首先在託管代碼中聲明一個類,類的屬性與JSON對象的屬性一致(不必完全一致),然後在託管代碼中將ScriptObject對象轉換成聲明的這個類型即可。 下面是一個完整的例子: Page.xaml: <UserControl x:Class="SilverlightApplication1.Page" xmlns="http://schemas.microsoft.com/client/2007" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="600" Height="480"> <Grid x:Name="LayoutRoot" Background="White"> <Canvas Canvas.Top="20"> <TextBlock Canvas.Top="10" Canvas.Left="20">請輸入您的姓名: </TextBlock> <TextBox x:Name="UserInput" Width="200" Height="30" Canvas.Top="40" Canvas.Left="20"></TextBox> <TextBlock x:Name="Msg" Canvas.Top="90" Canvas.Left="20" Foreground="Navy" FontSize="18" Width="500"></TextBlock> <Button Click="Button_Click" Content="單擊我" FontSize="24" Width="160" Height="60" x:Name="BtnTest" Canvas.Top="160" Canvas.Left="20"></Button> <Button Click="JSONButton_Click" Content="JavaScript JSON 對象測試" FontSize="24" Width="300" Height="50" Canvas.Top="240" Canvas.Left="20"></Button> <TextBlock x:Name="Msg2" Canvas.Top="300" Canvas.Left="20" Foreground="Navy" FontSize="18" Width="500"></TextBlock> <TextBlock x:Name="Msg3" Canvas.Top="320" Canvas.Left="20" Foreground="Navy" FontSize="18" Width="500"></TextBlock> </Canvas> </Grid> </UserControl> Page.xaml.cs: using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.Windows.Browser; using System.Runtime.Serialization.Json; namespace SilverlightApplication1 { public partial class Page : UserControl { public Page() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { string UserInputContent = this.UserInput.Text; if (UserInputContent.Equals(String.Empty)) { UserInputContent = "Hello Silverlight World!"; } else { UserInputContent = "你好," + UserInputContent; } HtmlWindow win = HtmlPage.Window; this.Msg.Text = UserInputContent; win.Alert("Silverlight 裏面彈出的對話框。 " + UserInputContent); //執行頁面中的js函數: win.Eval("getArrayTest()"); Object[] args = { "將此參數傳遞給 js 函數" }; win.Invoke("getArrayTest", args); //如果頁面中的值 HtmlDocument doc = HtmlPage.Document; doc.GetElementById("UserName").SetAttribute("value", this.UserInput.Text); } [ScriptableMember()] public string InterInvole() { string username = HtmlPage.Document.GetElementById("UserName").GetAttribute("value"); this.UserInput.Text = username; this.Msg.Text = "您輸入了:" + username; return "你從js腳本中調用了 Silverlight 裏面的方法。"; } private void JSONButton_Click(object sender, RoutedEventArgs e) { ScriptObject so = HtmlPage.Window.Invoke("ReturnObject", null) as ScriptObject; Staple s = so.ConvertTo<Staple>(); this.Msg2.Text = "大家好,我在 JavaScript JSON 對象中的名稱是:" + s.UserName; } //接受Html頁面傳遞的 JSON 字符串 [ScriptableMember()] public void ReveiveJSON(string jsonString) { //注意引用:System.Runtime.Serialization.Json DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(Staple)); System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.Encoding.Unicode.GetBytes(jsonString)); Staple staple = new Staple(); staple = (Staple)json.ReadObject(ms); Msg3.Text = "UserId = " + staple.UserId.ToString() + " , UserName = " + staple.UserName; } } public class Staple { public string UserName { set; get; } public Double UserId { set; get; } } } App.xaml.cs: using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.Windows.Browser; namespace SilverlightApplication1 { public partial class App : Application { public App() { this.Startup += this.Application_Startup; this.Exit += this.Application_Exit; this.UnhandledException += this.Application_UnhandledException; InitializeComponent(); } private void Application_Startup(object sender, StartupEventArgs e) { // Load the main control Page p = new Page(); HtmlPage.RegisterScriptableObject("SilverlightApplicationExample", p); // 請注意這裏的定義方法,如果這裏的p寫成 new Page(),則Javascript基本不能給 UserInput 賦值! this.RootVisual = p; } private void Application_Exit(object sender, EventArgs e) { } private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e) { } } } SilverlightApplication1TestPage.aspx: <%@ Page Language="C#" AutoEventWireup="true" %> <%@ Register Assembly="System.Web.Silverlight" Namespace="System.Web.UI.SilverlightControls" TagPrefix="asp" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Silverlight 2託管代碼與Javascript交互的例子</title> <script type="text/javascript"> //<!{CDATA[ //定義全局變量: var testVar = "孟憲會"; //定義全局函數: function getArrayTest() { if(arguments.length > 0) { alert("js 對話框:您傳遞了參數。" + arguments[0]); return arguments[0]; } else { alert("js 對話框:無參數調用。"); return "js 函數返回值"; } } function SetUserName() { alert(SilverlightPlugin.Content.SilverlightApplicationExample.InterInvole()); } var Staple = { UserId:100, UserName:'孟憲會', SayHello:function(){alert(this.UserName)} }; function ReturnObject() { return Staple; } function SendJSONToSilverlight() { SilverlightPlugin.Content.SilverlightApplicationExample.ReveiveJSON(JSON.stringify(Staple)); } //定義Silverlight插件對象 var SilverlightPlugin = null;; function pluginLoaded(sender) { SilverlightPlugin = sender.get_element(); } //]]> </script> <script src="json2.js" type="text/javascript"></script> <!-- http://www.JSON.org/json2.js --> </head> <body style="height: 100%; margin: 0;"> <form id="form1" runat="server"> <div style="border: 2px solid #EEE; margin: 20px;padding:20px"> 請輸入你的名字:<input id="UserName" type="text" value="" /> <input type="button" onclick="SetUserName()" value="將名字傳遞到 Silverlight" /> <input type="button" onclick="SendJSONToSilverlight()" value="將JSON傳遞到 Silverlight" /> </div> <br /> <div style="border: 2px solid #EEE;margin: 20px;"> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <asp:Silverlight ID="Xaml1" runat="server" OnPluginLoaded="pluginLoaded" Source="~/ClientBin/SilverlightApplication1.xap" Version="2.0" Width="600px" Height="480px" /> </div> </form> </body> </html> 單擊“JavaScript JSON 對象測試”按鈕,運行結果如下:
|
關鍵字:Silverlight 2學習教程 |