Reach Out And Touch HTML

I've posted a new video that shows how Silverlight 1.1 lets you create custom controls that can reach out to the HTML host page. In the example, we not only touch HTML controls, but we also respond to events (a button press) on an HTML control. The enabling technology is in the name space System.Windows.Browser.

The work turns on creating HtmlElement objects as member variables of your class.  These objects have an AttachEvent method that takes the name of the event and an event handler as arguments, as shown in this snippet:


private HtmlElement newMessageTextBox;
private HtmlElement updateButton;
private HtmlElement fontSizeTextBox;

public void Page_Loaded(object o, EventArgs e)
{
    InitializeComponent();

    HtmlDocument document = HtmlPage.Document;
    newMessageTextBox = document.GetElementByID("messageInput");
    updateButton = document.GetElementByID("update");
    updateButton.AttachEvent(
        "onclick", 
        new EventHandler(this.updateButton_Click)
    );
}

The HtmlPage is able to get the current (HTML) Document and from that we can get the (HTML) TextBox that was placed on the Document. With the document in hand, we can get the button, declared in TestPage.html as

<

input id="update" type="button" value="Update" />

With a reference to the button, we can add the event handler that we can then implement in managed code. Very slick and reverses the visibility that was required in 1.0 (in which the HTML page was reaching into the Silverlight control).

 

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. His latest book, Building APIs with .NET will be released early in 2025. Liberty is a Senior SW Engineer for CNH and he was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Microsoft MVP.
This entry was posted in z Silverlight Archives. Bookmark the permalink.