Friday, April 10, 2009

How to use Html Div in silverlight using Silverlight Html bridge

We all understand that Silverlight has not matured into a full blown Line of Business Applications platform and time and again we have to interact with HTML Dom for most of our work. I've tried to consolidate how to access an existing element and add a new div element dynamically. Let's look at how to access the existing elements and do some modifications to it.



This is the DIV you are supposed see some changes when you click buttons. But this is not working yet because of incompatibility with blogger and the xap hosting.




Accessing the existing elements:
Silvelright packages all the Html Dom content under the System.Windows.Browser assembly/namespace. Let's assume we have a div in our Html page where the silverlight control is going to be hosted.
I've tried both setting as well as getting the innerhtml property of the div control we used. The code for the Div in your html or aspx page is added as follows.

<div id="silverlightdiv">
<p>hello world</p>
</div>

Now our Page.xaml.cs will be able to access the "silverlightdiv" using HtmlElement properties. A short snippet for getting and setting the property are as below.
Getting the InnerHtml property:

HtmlElement mysilverlightdiv = HtmlPage.Document.GetElementById("silverlightdiv");
Object obj = mysilverlightdiv.GetProperty("innerhtml");
String str = obj.ToString();
MessageBox.Show(str);

Setting the InnerHtml property:

HtmlElement mysilverlightdiv = HtmlPage.Document.GetElementById("silverlightdiv");
mysilverlightdiv.SetProperty("innerhtml", txtHtmlText.Text);

This technique do not use the overlay (which needs the windowless=true to be set), but uses the HTML Dom bridge provided by silverlight. Also for setting the CSS properties of the div should be done using the SetStyleAttribute funtion of the HtlmElement class. A look at the code snippet for changing an attribute is as follows.
Setting a CSS Property:

HtmlElement mysilverlightdiv = HtmlPage.Document.GetElementById("silverlightdiv");
mysilverlightdiv.SetStyleAttribute("color", "red" );

Download Source


You can download the Visual Studio 2008 control source file/project from HtmlSilverlight.

3 comments:

Unknown said...

Hi
The link to the source code is broken.

muthu.v said...

Hi iiordanov,
Thanks for the note. I have fixed the link now.

Muthu

Unknown said...

shnaHi, This Htmlhost is very nice.

But I need to place this control in a drag dock panel. My controls are in this higherarchy.
Dragdockpanelhost-->
Dragdockpanel-->
Stackpanel as content of dragdockpanel.
Now, I have added this htmlhost as child to stackpanel.

This htmlhost control is not embeded into the stackpanel though i add it as child of it.

Can you plz help me how to do this??