Apr 2, 2008

Using HTML in Silverlight

As Silverlight gets more and more matured, people start to ask more and more about the controls which the platform provides. One of my hopes in dealing with Silverlight was the ability to embed HTML content. Alas, there is no control that will allow me to do so. There are 2 ways to resolve this problem: code your own control that will handle some or all HTML capabilities, or create a wrapper around the browser. I chose option 2.

How do we wrap around the browser?
Luckily, Silverlight exposes almost all DOM objects to the Silverlight application. Using this, a Silverlight application can create new or modify any existing HTML elements in the parent HTML document. Example:

HtmlElement elem = HtmlPage.Document.CreateElement("div");
HtmlPage.Document.Body.AppendChild(elem);

With the help of some CSS, this element can be placed anywhere in the browser window. Example:

elem.SetStyleAttribute("position", "fixed");
elem.SetStyleAttribute("width", "auto");
elem.SetStyleAttribute("top", "150px");
elem.SetStyleAttribute("left", "250px");

The final bit is filling this element with actual content. To do this, I've used a JavaScript helper function that I placed in the parent document. Finally, I use the HtmlPage.Window.Invoke API to call the helper function and place the HTML content into my HTML element.

Some additional info on how to do these things can be found at:
Walkthrough: Calling Managed Code from Client Script
Walkthrough: Calling Client Script from Managed Code

Edit:
There is the possibility of inserting HTML content inside this element without the need for calling an external JavaScript function. This is done by using HtmlElement.SetAttribute to set the innerHTML attribute to whatever HTML content it must be.

No comments: