使用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 />

  2)在Silverlight页面的构造函数中增加下面代码:

  HtmlElement elementTxtShow = HtmlPage.Document.GetElementById("txtShow");
      elementTxtShow.SetAttribute("value", "init name");

 

  3. 为html元素添加事件

  1)向html页面增加一个button,如下:

  <input />

  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 />
            </a>
        </object>


        <input />

 

  以下为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

相关文章:

  • 2021-08-09
  • 2021-07-24
  • 2022-12-23
  • 2021-06-15
  • 2021-09-16
  • 2021-07-09
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-02-22
  • 2022-12-23
  • 2021-10-05
  • 2022-03-04
  • 2021-07-23
相关资源
相似解决方案