韩寒的电视剧:Silverlight and Javascript Interaction | Switch on the Code

来源:百度文库 编辑:九乡新闻网 时间:2024/05/04 07:31:12

Silverlight and Javascript Interaction

Posted in:

Related Posts

  • Communicate Between Flex and Silverlight using Javascript
  • Silverlight Tutorial - Interaction With The DOM
  • How To Embed Silverlight Into a Webpage
  • How to Use Custom User Controls in Silverlight

March 2008 - Important Note

This tutorial is no longer valid. It was written for MicrosoftSilverlight 1.1 Alpha Refresh, which no longer exists - it has beenreplaced by Silverlight 2. We have left the page up for historicalpurposes (and because there are incoming links). Once again, theinformation below is invalid and in some cases misleading forSilverlight 2.


Silverlight is a relatively new client side technology released byMicrosoft, but already people are finding the need to communicatebetween their Silverlight applications and Javascript. This tutorialwill go through all the code required to call Javascript functions fromSilverlight and vice-versa.

All the Silverlight code and examples were created using the 1.1Alpha Refresh. Before you can use the example application below, you'llneed to download the runtime (if you haven't already). If you're new to Silverlight, check out our introductory tutorial for information on what to download and how to get started.

Before we jump into code, let's look at an example of somecommunication between Silverlight and Javascript. The application onthe left was created using Silverlight, the one on the right was madeusing HTML and CSS. When one of the buttons on the left is clicked, amessage will be displayed on the right indicating that. The same thinghappens when a button on the right is clicked.

Edit: Example Obsoleted And Removed

So let's see how something like this is done. We'll start with thehard one - calling a Javascript function from Silverlight. There's nodirect way (that I know of) to simply call a Javascript functiondirectly from the Silverlight code behind. What we have to do is createevents and attach to them from the Javascript code. This isn't a lotof work, but being able to call them directly would be a nice feature tohave. So let's look at some C# code behind that creates the events.

 

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

namespace SilverlightJavascript
{
  [Scriptable]
  public partial class Page : Canvas
  {
    [Scriptable]
    public event EventHandler ButtonAClicked;
    [Scriptable]
    public event EventHandler ButtonBClicked;
    [Scriptable]
    public event EventHandler ButtonCClicked;

    public void Page_Loaded(object o, EventArgs e)
    {
      // Required to initialize variables
      InitializeComponent();

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

 

Since my Silverlight application has three buttons, I created threeevents - one for each button. They're created and used exactly likethey are in an ordinary C# Windows application. One difference I'm sureyou noticed is the [Scriptable] attribute above thedefinition of the class and each event. This lets Silverlight know thatthis class and these events should be accessible from the Javascriptcode. The next thing you might have noticed is the RegisterScriptableObjectcall. With this function we're telling Silverlight to make this classaccessible via scripts by the name "SilverlightApp". Now whenever Iwant to use this object in Javascript, I'll reference it by the name"SilverlightApp". We'll see how this works later. Now that everythingis setup, let's look at some C# code to fire our newly created events.

 

void ButtonA(object sender, MouseEventArgs e)
{
  if (ButtonAClicked != null)
    ButtonAClicked(this, e);
}

void ButtonB(object sender, MouseEventArgs e)
{
  if (ButtonBClicked != null)
    ButtonBClicked(this, e);
}

void ButtonC(object sender, MouseEventArgs e)
{
  if (ButtonCClicked != null)
    ButtonCClicked(this, e);
}

 

In my XAML code I hooked up a MouseLeftButtonUp event toeach of my buttons. Now when a button is clicked, one of thesefunctions will be called. As you can see, firing the events is nodifferent than a C# application. You should always make sure to checkthat an event is not null before firing it - otherwise things tend tocrash. An event will be null if nothing has attached to it.

That's all the code required on the Silverlight side to callJavascript functions. Now let's look at how to make Javascript listenfor these events. The first thing we need to do is attach Javascriptfunctions to each event. We'll do this as soon as the Silverlightapplication is done loading. So now you're probably wondering, how dowe know when the Silverlight is done loading? There's an event we canlisten for that is called as soon as it's finished. In order to getthis event we need to modify the Javascript that Visual Studio generatedas part of the test code. In my solution, the .js file is namedTestPage.html.js. It might be different for you depending on how youset it up.

 

// 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();
  }
}

 

This should look very similar to what Visual Studio has created for you. The addition we have to make is in the events: {} section. We need to add an event for onLoad. With this addition, we're telling Silverlight to call the Javascript function OnLoaded as soon as it's finished loading. The OnLoaded function is where we're going to be attaching Javascript functions to our Silverlight events. So let's see how that's done.

 

function OnLoaded(sender, args)
{
  sender.Content.SilverlightApp.ButtonAClicked = ButtonAClicked;
  sender.Content.SilverlightApp.ButtonBClicked = ButtonBClicked;
  sender.Content.SilverlightApp.ButtonCClicked = ButtonCClicked;
}

function ButtonAClicked()
{
  //The Silverlight A button has been clicked
}

function ButtonBClicked()
{
  //The Silverlight B button has been clicked
}

function ButtonCClicked()
{
  //The Silverlight C button has been clicked
}

 

The OnLoaded event is automatically passed in theSilverlight object and some event arguments. Here's where we use the"SilverlightApp" name we created above. With those assignments, we'retelling Silverlight to execute a Javascript function whenever one ofthose events is fired. So now, whenever the event ButtonAClicked is fired from the Silverlight Application, the Javascript function ButtonAClicked will be executed.

That's it for calling Javascript functions from Silverlight. Nowlet's look at how to call Silverlight functions from Javascript. Thisprocess is much easier than calling Javascript from Silverlight. Thefirst thing we need is a C# function we want called. Let's add one toour Silverlight code behind.

 

[Scriptable]
public void HTMLButtonAClicked()
{
  //The HTML A button has been clicked
}

 

There nothing special about this function except for the [Scriptable] attribute which makes it accessible by our Javascript code. All that's left is to call this function from the Javascript code.

 

var slApp = document.getElementById('SilverlightControl');
slApp.Content.SilverlightApp.HTMLButtonAClicked();

 

As you can see, this is much easier than the other way around. Thefirst thing we need to do is get the Silverlight object. You'reprobably wondering where the "SilverlightControl" id came from which ispassed into getElementById. This is set back in the .jsfile that Visual Studio created for you. All that's left to do isaccess the class we named "SilverlightApp" and call the HTMLButtonAClicked function. Once that's done, the function we wrote in the C# code behind will be executed.

I hoped you enjoyed this tutorial on Silverlight and Javascript interaction. Post a comment if you have any questions.