使用Silverlight,通过简单的代码就可以实现诸如silverlight与html元素,silverlight与javascript的互操作。首先要说明的是,在silverlight和html交互操作中,我们必须要引用System.Windows.Browser这个命名空间
以下是以“Hello world"为例实现的相关方法。
一、Silverlight操作Html元素
1. 先从简单的入手,修改页面标题。
我们可以在Silverlight页面的构造函数中增加下面代码来实现:
HtmlPage.Document.SetProperty("title", "The title is seted by silverlight...");
2. 设置Html元素的属性值
1)在html页面上增加一个文本框,用来被Silverlight调用,如下:
<input id="txtName" type="text" />
2)在Silverlight页面的构造函数中增加下面代码:
HtmlElement elementTxtShow = HtmlPage.Document.GetElementById("txtShow");
elementTxtShow.SetAttribute("value", "init name");
3. 为html元素添加事件
1)向html页面增加一个button,如下:
<input id="btnSayHello" type="button" value="Say hello" />
2)通过Silverlight为它设置服务端事件
HtmlElement btnSetName = HtmlPage.Document.GetElementById("btnSayHello");
btnSetName.AttachEvent("onclick", delegate(object sender, HtmlEventArgs he)
{
HtmlElement element = HtmlPage.Document.GetElementById("txtShow");
element.RemoveAttribute("value");
element.SetAttribute("value", "Hello world!");
});
汇总代码,以下为html需要增加的元素:
<object id="silverlightControl" data="data:application/x-silverlight-2," type="application/x-silverlight-2"
width="100%" height="100%">
<param name="source" value="ClientBin/*.xap" />
<param name="onError" value="onSilverlightError" />
<param name="background" value="white" />
<param name="minRuntimeVersion" value="4.0.50826.0" />
<param name="autoUpgrade" value="true" />
<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>
<input id="btnSayHello" type="button" value="Say hello" />
<input id="txtShow" type="text" />
以下为silverlight的C#代码,在构造函数中添加
HtmlPage.Document.SetProperty("title", "The title is seted by silverlight...");
HtmlElement elementTxtShow = HtmlPage.Document.GetElementById("txtShow");
elementTxtShow.SetAttribute("value", "init text");
HtmlElement btnSetName = HtmlPage.Document.GetElementById("btnSayHello");
btnSetName.AttachEvent("onclick", delegate(object sender, HtmlEventArgs he)
{
HtmlElement element = HtmlPage.Document.GetElementById("txtShow");
element.RemoveAttribute("value");
element.SetAttribute("value", "Hello world!");
});
接着下面文章介绍通过javascript调用silverlight