在上一篇Blog文章中,讲述了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 里面d出的对话框。 " + 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#" @R_301_6843@EventWireup="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学习教程(六): Silverlight托管代码调用Javascript中的JSON对象全部内容,希望文章能够帮你解决Silverlight 2学习教程(六): Silverlight托管代码调用Javascript中的JSON对象所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)