Monday, April 13, 2009

Dynamically creating a DIV control in Silverlight

By now everyone would have gotten a clear idea that HtmlPage, HtmlDocument along with HtmlElement is the way to display a div item in silverlight pages. Now here are few samples to create some controls dynamically from a silverlight page using Html Dom bridge.
For those who wonder what is the difference between a Html Silverlight Dom bridge and HTML Overlay, Html overlay needs the windowless parameter to be set and gives the rendering job to the browser, but Html Silverlight Dom model won't.
There is an excellent FAQ article by erikreitan on the Html and Java script in silverlight http://blogs.msdn.com/erikreitan/archive/2008/12/02/silverlight-html-bridge-faq.aspx. Take a look at this article when you get some time.

HtmlDocument doc = HtmlPage.Document;
HtmlElement dynamicDiv = doc.CreateElement("div");
dynamicDiv.SetAttribute("id", System.Guid.NewGuid().ToString());
dynamicDiv.SetStyleAttribute("height", "20px");
dynamicDiv.SetStyleAttribute("width", "800px");
dynamicDiv.SetProperty("innerhtml", "A small sample of dynamically added div from silverlight");
doc.Body.AppendChild(dynamicDiv);

Remember to include the 'System.Windows.Browser' namespace for this code to compile.

1 comment:

mkoswell said...

Nice blog, just bookmarked it for later reference. I like your blog currently we are looking for this article! Thanks for all of the code. It will come in handy one day I'm sure!

If you do not mind, please visit my article related to travel to Pandeglang district in Banten, Indonesia at Kenali dan Kunjungi Objek Wisata di Pandeglang

Best regards