安装Silverlight

开发Silverlight

一步一步学Silverlight 2系列(21):如何在Silverlight中调用JavaScript

概述

Silverlight 2 Beta 1版本发布了,无论从Runtime还是Tools都给我们带来了很多的惊喜,如支持框架语言Visual Basic, Visual C#, IronRuby, Ironpython,对JSON、Web Service、WCF以及Sockets的支持等一系列新的特性。《一步一步学Silverlight 2系列》文章将从Silverlight 2基础知识、数据与通信、自定义控件、动画、图形图像等几个方面带您快速进入Silverlight 2开发。

Silverlight中内置了对于HTML、客户端脚本等的支持。很多情况下,我们编写的Web应用程序中用了一些JavaScript或者AJAX框架,我们希望能够在Silverlight调用某些脚本方法,或者说在Silverlight中触发某个脚本的执行,这时就需要用到在Silverlight中调用JavaScript,本文将简单介绍这一内容。

使用GetProperty获取脚本对象

先来看一个简单的例子,在Silverlight测试页面中放入一个div用作显示信息:

<div id="result"></div>

编写一段简单的JavaScript代码:

<script type="text/javascript">
    function Hello(message)
    {
        var resultSpan = $get("result");
        resultSpan.innerText = "Hello " + message;
    }
</script>

再编写一个简单的输入信息界面:

<StackPanel Background="#CDFCAE" Orientation="Vertical">
    <StackPanel Height="40">
        <TextBlock Text="Calling Browser Script from Silverlight"
                   Foreground="Red"></TextBlock>
    </StackPanel>
    <StackPanel Orientation="Horizontal">
        <TextBox x:Name="input" Width="340" Height="40" Margin="20 0 20 0"></TextBox>
        <Button x:Name="submit" Width="120" Height="40" Background="Red"
            Content="调 用" FontSize="20" Foreground="Red" Click="submit_Click"></Button>
    </StackPanel>
</StackPanel>

实现对脚本的调用:

private void submit_Click(object sender, RoutedEventArgs e)
{
    ScriptObject hello = HtmlPage.Window.GetProperty("Hello") as ScriptObject;
    hello.InvokeSelf(this.input.Text);
}

ScriptObject提供了任何客户端脚本的封装,不仅仅是JavaScript,使用其他的AJAX框架也可以,如jQuery等。然后调用InvokeSelf()方法,传入参数,这里ScriptObject总共提供了两个方法,Invoke和InvokeSelf,如果我们只调用脚本对象的自身,就可以使用InvokeSelf,如果脚本对象中还有其它的函数等,可以使用Invoke传入名称进行调用,两个方法的定义如下:

[SecuritySafeCritical]
public virtual object Invoke(string name, params object[] args);

[SecuritySafeCritical]
public virtual object InvokeSelf(params object[] args);

运行上面的示例:

TerryLee_Silverlight2_0097

输入TerryLee后点击调用,可以看到确实调用了客户端脚本:

TerryLee_Silverlight2_0098

使用CreateInstance创建脚本对象

除了使用上面所说的使用HtmlPage.Window.GetProperty方法获取脚本对象之外,还有一种替代方法,即使用HtmlPage.Window属性的CreateInstance方法。还是使用上面的示例,我们在测试页中加入如下一段脚本,使用prototype为myHello添加了显示的功能:

<script type="text/javascript">
    myHello = function(message)
    {
        this.Message = message;
    }
    myHello.prototype.Display = function()
    {
        var resultSpan = $get("result");
        resultSpan.innerText = "Hello " + this.Message;
    }
</script>

使用HtmlPage.Window.CreateInstance创建脚本对象

private void submit_Click(object sender, RoutedEventArgs e)
{
    ScriptObject script = HtmlPage.Window.CreateInstance("myHello",this.input.Text);

    object result = script.Invoke("Display");
}

运行后的效果跟上面的示例是一样的,如:

TerryLee_Silverlight2_0097

输入文本信息后:

TerryLee_Silverlight2_0099

使用HtmlPage.Window.Eval()

最后还有一种机制,就是使用HtmlPage.Window.Eval()方法,只要我们给该方法传入一段字符串,它都会作为JavaScript来执行。做一个简单的测试,我们再修改一下上面的示例代码:

private void submit_Click(object sender, RoutedEventArgs e)
{
    HtmlPage.Window.Eval(this.input.Text);
}

运行后我们在文本框中输入一段脚本alert('TerryLee');,效果如下所示:

TerryLee_Silverlight2_0100

既然HtmlPage.Window.Eval()可以执行一段脚本,并且将执行的结果以对象形式返回,我们可以使用它来获取DOM元素。如下面这段代码:

private void submit_Click(object sender, RoutedEventArgs e)
{
    HtmlElement result = HtmlPage.Window.Eval("document.getElementById('result')") as HtmlElement;

    string message = result.GetAttribute("innerHTML");
    HtmlPage.Window.Alert(message);
}

运行后效果如下,获取的result确实就是我们定义的div。

TerryLee_Silverlight2_0101

对AJAX框架的支持

前面说过,ScriptObject不仅仅是对JavaScript的封装,也支持其它的AJAX框架,现在我们用jQuery来测试一下,编写一小段代码:

<script type="text/javascript">
    function myHello(message)
    {
        $("#result").text("Hello " + message);
    }
</script>

调用脚本

private void submit_Click(object sender, RoutedEventArgs e)
{
    ScriptObject script = HtmlPage.Window.GetProperty("myHello") as ScriptObject;

    script.InvokeSelf(this.input.Text);
}

运行后的结果与前面的示例是一样的:

TerryLee_Silverlight2_0102

结束语

本文介绍了在Silverlight中调用JavaScript的几种方法,下一篇我将介绍如何在JavaScript中调用Silverlight。

Your rating: None Average: 3.7 (3 votes)

评论

The hottest new traditional and seasonal

coach outlet store online

. Keep up to date with the latest trends. Look at this zip top closure with colorful C logo printed fabric bag.You may find the most affordable Bags here.
This brown handbag called Flagship Signature Brown Handbag has been the best seller in the

coach factory outlet

for almost three weeks.
Everyone believes the fact that

coach outlet store online

can be well-known simply because of its high quality and the lovely pattern.
My friend is dying to get a coach purse at

coach outlet store

because all of her friends have them at work. They earn great reputation from many people.
The latest fashion collection contains those bags suitable to be worn in both casual and formal environment. We provide the best quality

louis vuitton uk

with the most reasonable price we can offer as you see in our online store.
in fact,

louis vuitton

is one of the most famous fashion design master.he opened the fist suitcase shop called after his name.

louis vuitton outlet

,welcome to buy urban louis vuitton on our online shop.discount price is our special offer, durability and high quality is our promise.
They're not chosen, so one of these ideal for you.For more flexibleness a lot more like these, there are lots of discount 'shoulder' variations outlet

louis vuitton bags

.
Show someone how much you care with this sophisticated and sparkling

christian louboutin

collection. Cut with exquisite detail, this can be a beautiful yet practical gift.
All of the

armani watches

Denim handbags at the High quality, practical, timeless yet resolutely modern design with our professional and excellent service.
You can choose the discount Louis Vuitton bags on our website. Cheap

emporio armani watches

are specifically designed to make a statement of fashion and elegance..
With the safe door to door shipping, the

gucci outlet

will send the products to your hands, which are of top quality and at competitive factory prices.
One of my friend wants to buy a gift for her mother on the Mother's Day. She asks me, I suggest her to buy

hermes bags

, which has good quality and unique design.
I can't wait sharing the

hermes birkin

with you.It's an online crystal shopping paradise supplying delicate Swarovski jewelry.














, to appear more complex mixture of modern Miscellaneous function ed hardy electronic hand accounts, MP3, cell phone watch appear. And some ed hardy , to appear more complex mixture of modern Miscellaneous function heels electronic hand accounts, MP3, cell phone watch appear. And some blahnik mary janes , to appear more complex mixture of modern Miscellaneous function wholesale fashion jewelry by the dozen electronic hand accounts, MP3, cell phone watch appear. And some hip hop jewelry wholesale , to appear more complex mixture of modern Miscellaneous function brian atwood loca stud platforms electronic hand accounts, MP3, cell phone watch appear. And some louboutin and ballerina pumps

ighty woman, rich and splendid. Tenuous leather watchband caters to hermes handbags outlet this mighty gas field. You need a big dial male christian louboutin replica wholesale ighty woman, rich and splendid. Tenuous leather watchband caters to louboutin hot red pumps this mighty gas field. You need a big dial male designer heels ighty woman, rich and splendid. Tenuous leather watchband caters to ed hardy clothing this mighty gas field. You need a big dial male ed hardy ighty woman, rich and splendid. Tenuous leather watchband caters to discount sterling silver jewelry this mighty gas field. You need a big dial male 925 silver jewelry