韩将公布萨德选址:HTML Bridge: Silverlight.NET

来源:百度文库 编辑:九乡新闻网 时间:2024/04/28 13:15:33

HTML Bridge

By Microsoft Silverlight Team|March 5, 2009|Level 300 : Intermediate

Summary

HTML Bridge is a technology in Silverlight that enablesyou to access the HTML Document Object Model (DOM) from managed code,and to call managed code from JavaScript. This QuickStart demonstrateshow to use some of the HTML Bridge types in Silverlight.

This QuickStart contains the following sections:

  • HTML Bridge Overview
  • Setting Up the Silverlight Plug-in
  • Accessing the HTML DOM from Managed Code
  • Calling Managed Code from JavaScript

HTML Bridge Overview

HTML Bridge is an integrated set of types and methods that enable you to do the following:

  • Attach Silverlight managed event handlers to HTML controls.
  • Attach JavaScript event handlers to Silverlight controls.
  • Expose complete managed types to JavaScript for scripting.
  • Expose individual methods of managed types to JavaScript for scripting.
  • Use managed containers for DOM elements such as window, document, and standard HTML elements.
  • Pass managed types as parameters to JavaScript functions and objects.
  • Return managed types from JavaScript.
  • Control various security aspects of your Silverlight-based application.

Setting Up the Silverlight Plug-in

The examples in this QuickStart are text-based, so the Silverlightplug-in does not have to display any XAML-based UI elements. Therefore,the width and height of the Silverlight plug-in can be set to 0 pixelsto prevent it from occupying the Web page or interrupting normal HTMLflow. Although the Silverlight plug-in does not have a visible UI, itstill has access to the underlying DOM of the page.

The following HTML is embedded in this page. It applies to the two examples in this QuickStart.

HTML


                         type="application/x-silverlight-2"
                     width="0px" height="0px">
       
       
       
       
       
                      style="text-decoration: none;">
                                  alt="Get Microsoft Silverlight" style="border-style: none"/>
       

   

   

If you set the display:none or visibility:hiddenstyles on the Silverlight plug-in or its containing DIV, theSilverlight plug-in will not be able to access the page's underlyingDOM.

Accessing the HTML DOM from Managed Code

HTML Bridge includes several types that enable you to access andmodify the HTML DOM from Silverlight. The following example demonstrateshow to access the HTML DOM and performs the following operations inmanaged code:

  • Enables the first text box.
  • Sets the text for the first text box to "This text is set from managed code."
  • Attaches a Silverlight event handler to the Convert button.
  • Converts the text in the first text box to uppercase and displays it in the second text box.

To try this example, add text to the first text box and click the Convert button.The text is converted to uppercase and displayed in the second text box.

  Enter lowercase text    

  Convert to uppercase  

  Uppercase text      

 

The following HTML creates the two text boxes and the button. Notice that it has the following characteristics:

  • The text box named Input is disabled.
  • Each element has an ID value, which is helpful when you need to access the element from Silverlight.
  • Inline HTML event handlers are not assigned.
  • Although the entire file is not listed, there are no embedded JavaScript handlers.

HTML


Enter lowercase text

Convert to uppercase

Uppercase text      
 

Accessing the HTML DOM

To access the HTML DOM from Silverlight, you typically use the following HTML Bridge classes:

  • HtmlPage represents the Web page. HtmlPage is static and is the main entry point for all DOM access.
  • HtmlDocument represents the document object.
  • HtmlElement represents DOM elements.

To use the HTML Bridge classes in managed code, you must add a using or Imports statement to the System.Windows.Browser namespace. Individual HTML elements can be accessed if they have an ID by using the HtmlDocument.GetElementById method. You can get properties and attributes on an element by using the HtmlElement.GetProperty and HtmlElement.GetAttribute methods. You can set properties and attributes on an element by using the HtmlElement.SetProperty and HtmlElement.SetAttribute methods.

The following managed code in the Page.xaml (Page.xaml.cs orPage.xaml.vb) file shows how you access the HTML DOM from Silverlight.This code is in thePage constructor and runs during application startup. The code gets a reference to the Input element, sets the disabled property to false, and sets the value attribute to "This text is set from managed code."

C#

public Page()
{
    InitializeComponent();
    HtmlDocument htmlDoc = HtmlPage.Document;
    HtmlElement  htmlEl  = htmlDoc.GetElementById("Input");
    htmlEl.SetProperty("disabled", false);
    htmlEl.SetAttribute("value", "This text is set from managed code.");
    ...
}

Visual Basic

Public Sub New()
    InitializeComponent()
    Dim htmlDoc As HtmlDocument = HtmlPage.Document
    Dim htmlEl As HtmlElement  = htmlDoc.GetElementById("Input")
    htmlEl.SetProperty("disabled", False)
    htmlEl.SetAttribute("value", "This text is set from managed code.")
    ...
End Sub
 

Attaching a Managed Event Handler

Not only can you access the HTML DOM, you can also attach events to HTML controls that are handled in managed code. HtmlElement derives from HtmlObject, which includes the HtmlObject.AttachEvent method. This method enables you to attach a Silverlight event handler to an HTML element.

The following managed code in the Page.xaml (Page.xaml.cs or Page.xaml.vb) file shows how the Convert button's onclick handler is attached to a managed event handler named OnConvertClicked by using the HtmlObject.AttachEvent method. The code also shows the OnConvertClicked event handler, which gets the value attribute on the Input text box and sets the value attribute on the Output element to an uppercase string.

C#

public Page()
{
    InitializeComponent();
    HtmlDocument htmlDoc = HtmlPage.Document;
    HtmlElement  htmlEl  = htmlDoc.GetElementById("Input");
    ...
    // Add an event handler for the Convert button.
    htmlEl = htmlDoc.GetElementById("Convert");
    htmlEl.AttachEvent("onclick", new EventHandler(this.OnConvertClicked));
}

void OnConvertClicked(object sender, HtmlEventArgs e)
{
    HtmlDocument htmlDoc = HtmlPage.Document;
    HtmlElement input    = htmlDoc.GetElementById("Input");
    HtmlElement output   = htmlDoc.GetElementById("Output");
    output.SetAttribute("value", input.GetAttribute("value").ToUpper());
}

Visual Basic

Public Sub New()
    InitializeComponent()
    Dim htmlDoc As HtmlDocument = HtmlPage.Document
    Dim HtmlElement  htmlEl As HtmlElement  = htmlDoc.GetElementById("Input")
    ...
    ' Add an event handler for the Convert button.
    htmlEl = htmlDoc.GetElementById("Convert")
    htmlEl.AttachEvent("onclick", _
        New EventHandler(Of HtmlEventArgs)(AddressOf OnConvertClicked))
End Sub

Private Sub OnConvertClicked(ByVal sender As Object, ByVal e As HtmlEventArgs)
    Dim htmlDoc As HtmlDocument = HtmlPage.Document
    Dim input As HtmlElement    = htmlDoc.GetElementById("Input")
    Dim output As HtmlElement   = htmlDoc.GetElementById("Output")
    output.SetAttribute("value", input.GetAttribute("value").ToUpper)
End Sub

Calling Managed Code from JavaScript

HTML Bridge provides the ScriptableType and ScriptableMemberattributes. These attributes are used to mark managed types and membersas scriptable. After these attributes are applied to a type or member,the type must be instantiated with the new operator, and then registeredby using the HtmlPage.RegisterScriptableObject method. The type or method is then available to be called from JavaScript.

The following example demonstrates how to call managed code fromJavaScript. To try this example, add some text to the first text box andclick the Call Silverlight Scriptable method button. A dialog box appears that indicates that the managed SimpleMethodExample method was called and displays the text. When you click OK, the return string is displayed in the second text box.

  Enter the text to send      

  Call Silverlight method      

  Display the return string

The following HTML creates the two text boxes and the button. When you click the Call Silverlight Scriptable method button, the JavaScript Call_SL_Scriptable function is called.

HTML


Enter the text to send

Call Silverlight method

Display the return string  
 

JavaScript Call

The following shows the JavaScript Call_SL_Scriptable function. The JavaScript gets the text from the Text1 text box and passes it to the managed SimpleMethodExample method. The text that is returned from the method is displayed in the Text2 text box. The SimpleMethodExample method call has the following format:

  • SLPlugin is a reference to the Silverlight plug-in.
  • Content is an object that represents the plug-in area.
  • SL_SMT is the name that is used to register the managed object.
  • SimpleMethodExample is the managed method name that was marked as scriptable.

JavaScript

 

Scriptable Managed Code

The following shows the managed code in the Page.xaml (Page.xaml.cs or Page.xaml.vb) filethat the JavaScript Call_SL_Scriptable function calls. In the Page constructor, a new ScriptableManagedType is created and registered during application startup. This object is registered with the name SL_SMT by using the HtmlPage.RegisterScriptableObject method.

The ScriptableManagedType class definition appears after the Page constructor.ScriptableManagedType has one method named SimpleMethodExample that has the ScriptableMember attribute. SimpleMethodExample calls the HtmlWindow.Alert method with the passed-in string. It returns a string to the JavaScript function.

C#

public Page()
{
    InitializeComponent();

    // Create and register a scriptable object.
    ScriptableManagedType smt = new ScriptableManagedType();
    HtmlPage.RegisterScriptableObject("SL_SMT", smt);
}

public class ScriptableManagedType
{
    [ScriptableMember]
    public string SimpleMethodExample(string s)
    {
        HtmlPage.Window.Alert("You called the Silverlight 'SimpleMethodExample'\n" +
            "and passed this string parameter:\n\n" + s);
        return "Returned from managed code: " + s;
    }
}

Visual Basic

Public Sub New()
    InitializeComponent()

    ' Create and register a scriptable object.
    Dim smt As ScriptableManagedType = new ScriptableManagedType()
    HtmlPage.RegisterScriptableObject("SL_SMT", smt)
End Sub

Public Class ScriptableManagedType
    _
    Public Function SimpleMethodExample(ByVal s As String) As String
        HtmlPage.Window.Alert("You called the Silverlight 'SimpleMethodExample'" + _
            vbCrLf + "and passed this string parameter:" + vbCrLf + vbCrLf + s)
        Return "Returned from managed code: " + s
    End Function
End Class

See Also

  • HTML Bridge: Interaction Between HTML and Managed Code
  • Integrating Silverlight with a Web Page
  • System.Windows.Browser Namespace