silverlight 與 javascript 互動

來源:互聯網
上載者:User

摘要:

先介紹一下System.Windows.Browser命名空間下的幾個類, 接著介紹Silverlight如何操縱Html元素, 最後介紹如何從Javascript調用Silverlight的方法, 以及Silverlight調用Javascript方法.

1.System.Windows.Browser

Silverlight提供了一組對象來描述Html文件物件模型(DOM), 包括HtmlPage, HtmlDocument, HemlElement, HtmlElementCollection, 等等. 我們可以通過這些對象從Silverlight訪問Html頁面的內容, 如擷取某個Html元素, 導航到新的URL等.(ps:Silverlight 1.1 Complete API List )

首先看HtmlPage類, 其提供了瀏覽器資訊的靜態屬性BrowserInformation;提供的靜態方法Navigate, 可以方便的跳轉到其他的web頁.提供了Document屬性訪問Html Dom, 有了它就可以幹很多事了

HtmlDocument/HemlElement類用來訪問DOM, 有了DOM就可以像Javascript一樣做任何事了.

注意: 如果需要Silverlight可以訪問Html頁面的內容, 在建立Silverlight控制項的時候必須將enableHtmlAccess設為true.

2.Silverlight操縱Html

想象Javascript是怎麼訪問Html元素的, Silverlight也同樣可以.

修改頁面屬性:如修改頁面標題, HtmlPage.Document.SetProperty("title", "new title");

操縱html元素:

HtmlElement elem =  HtmlPage.Document.GetElementByID("btn");
elem.SetAttribute("value", "haha");
elem.GetAttribute("value");

elem.AttachEvent("onclick", delegate(object sender, HtmlEventArgs he){
                // ...
            });

3.Javascript調用Silverlight方法

Javascript要想調用Silverlight, Silverlight必須通過DOM提供給Javascript一個可操作的對象.

建立一個silverlight項目, 修改Page.xaml.cs如下:

using System;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;

namespace SilverlightProject1
{
    [Scriptable]
    public partial class Page : Canvas
    {
        public void Page_Loaded(object o, EventArgs e)
        {
            // Required to initialize variables
            InitializeComponent();           

            WebApplication.Current.RegisterScriptableObject("js", this);           
        }

       [Scriptable]
       public string CalledByJs(string name)
        {
            return "i'm silverlight, called by " + name;
        }
    }
}

修改TestPage.html如下:

<!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>
    <title>Silverlight Project Test Page </title>
    <script type="text/javascript" src="Silverlight.js"></script>
    <script type="text/javascript" src="TestPage.html.js"></script>
    <style type="text/css">
        .silverlightHost { width: 640px; height: 480px; }
    </style>
    <script type="text/javascript">
        function callSL()
        {
            var control = document.getElementById("SilverlightControl");
            var manager = control.Content.js;
            alert( manager.CalledByJs('js') );
        }
    </script>
</head>

<body>
    <div id="SilverlightControlHost" class="silverlightHost" >
        <script type="text/javascript">
            createSilverlight();
        </script>
    </div>
    <input id="btn" type="button" value="call silverlight method" onclick="callSL()" />
</body>
</html>

好像還不支援Silverlight方法返回一個複雜類型, 不過還好Silverlight內建了json的支援, 使用System.Windows.Browser.Serialization命名空間下JavaScriptSerializer序列化一下就ok了.

4.Silverlight調用Javascript方法

Silverlight無法直接調用javascript方法, 不過可以利用事件, 在Silverlight裡拋出事件, 在javascript響應該事件.

修改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="SilverlightProject1.Page;assembly=ClientBin/SilverlightProject1.dll"
        Width="640"
        Height="480"
        Background="White"
        >
  <TextBlock Text="call js method" MouseLeftButtonDown="OnClick"/>
</Canvas>

修改Page.xaml.cs如下:

using System;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Input;

namespace SilverlightProject1
{
    [Scriptable]
    public partial class Page : Canvas
    {
        public void Page_Loaded(object o, EventArgs e)
        {
            // Required to initialize variables
            InitializeComponent();           

            WebApplication.Current.RegisterScriptableObject("js", this);           
        }

        protected void OnClick(object sender, MouseEventArgs e)
        {
            if (this.CallJs != null )
            {
                EventHandler temp = this.CallJs;
                temp(this, EventArgs.Empty);
            }
        }

       [Scriptable]
        public event EventHandler CallJs;
    }
}

修改TestPage.html.js:在onLoad事件裡添加了對Silverlight拋出的CallJs 事件的響應.

// JScript source code

//contains calls to silverlight.js, example below loads Page.xaml
function createSilverlight()
{
    Silverlight.createObjectEx({
        source: "Page.xaml",
        parentElement: document.getElementById("SilverlightControlHost"),
        id: "SilverlightControl",
        properties: {
            width: "100%",
            height: "100%",
            version: "1.1",
            enableHtmlAccess: "true"
        },
        events: { onLoad : OnLoaded}
    });
    // Give the keyboard focus to the Silverlight control by default
    document.body.onload = function() {
      var silverlightControl = document.getElementById('SilverlightControl');
      if (silverlightControl)
      {
        silverlightControl.focus();
      }
    }
}

function OnLoaded(sender, args)
{
    sender.Content.js.CallJs = calledBySL;
}

function calledBySL(sender, args)
{
    alert("i'm js, called by silverlight");
}

done!

我嘗試了在Silverlight事件裡加了自訂的參數, javascript這邊好像接收不到??不知道是什麼原因.

總結:

Silverlight與Javascript的互操作的方式和Flex類似, 不過個人還是喜歡Silverlight的方式, C#的文法簡單清晰.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.