Silverlight提供一组对象来描述了Html文档对象模型,包括HtmlPage,HtmlDocument,HtmlElement,HtmlElementCollection等。
我们可以通过这些对象从Silverlight托管代码中访问Html页面的内容,如获取页面输入框的值,导航页面到新的URL等。
注意:如果需要Silverlight控件可以访问Html页面的内容,在创建Silverlight控件的时候必须将enableHtmlAccess设为True。
下面的示例演示了如何在Silverlight控件中,将信息显示到页面Div中,以及在Silverlight控件中导航页面。
TestPages.html
<head> <title>Silverlight Project Test Page </title> <script type="text/javascript" src"Silverlight.js"></script> "TestPage.html.js"><script> /head> <!-- Give the keyboard focus to the Silverlight control by default --> <body <br /> </> <div id"divTest" style"background-color: #C0C0C0; text-align: center; font-size: 30px;">显示Silverlight控件中获取的系统时间 /div> "SilverlightControlHost" > "text/javascript"> createSilverlight(); div> /body> /html>
Page.xaml
<Canvas x:Name="parentCanvas" xmlns="http://schemas.microsoft.com/client/2007" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Loaded="Page_Loaded" x:Class="SilverlightCN.Samples.HtmlPages.Page;assembly=ClientBin/SilverlightCN.Samples.HtmlPages.dll" Width="640" Height="480" Background="White" > <TextBlock x:Name="btnClickme" FontSize="40" Text="Show Date" MouseLeftButtonUp="btnClickme_OnMouseLeftButtonUp" Cursor="Hand" Canvas.Left="50" Canvas.Top="100"></TextBlock> <TextBlock x:Name="btnopenURL" FontSize="40" Text="Open URL" MouseLeftButtonUp="btnopenURL_OnMouseLeftButtonUp" Cursor="Hand" Canvas.Left="300" Canvas.Top="100"></TextBlock> <TextBlock x:Name="btnopenURLInNewWindow" FontSize="40" Text="Open URL in new window" MouseLeftButtonUp="btnopenURLInNewWindow_OnMouseLeftButtonUp" Cursor="Hand" Canvas.Left="550" Canvas.Top="100"></TextBlock> </Canvas>
using System; System.WindowsSystem.Windows.ControlsSystem.Windows.DocumentsSystem.Windows.InkSystem.Windows.InputSystem.Windows.MediaSystem.Windows.Media.AnimationSystem.Windows.ShapesSystem.Windows.browser; namespace SilverlightCN.Samples.HtmlPages { public partial class Page : Canvas { void Page_Loaded(object o,EventArgs e) { // required to initialize variables InitializeComponent(); } void btnClickme_OnMouseLeftButtonUpobject sender,MouseEventArgs e{ //通过 HtmlPage.Document获取到Html文档,然后在获取到指定元素 HtmlElement element = HtmlPage.Document.GetElementByID("divTest"; //设置Div的内容 element.SetAttribute"innerText",DateTime.Now.ToLongDateString; void btnopenURL_OnMouseLeftButtonUp{ //将该页导航到指定URL System.Windows.browser.HtmlPage.Navigate"http://silverlight.cn"void btnopenURLInNewWindow_OnMouseLeftButtonUp{ //在新窗口中打开指定的URL "http://silverlight.cn","_blank"} } }