Silverlight Tip of the Day #56 – Accessing the HTML DOM from Silverlight.
In Silverlight you can interact directly with the HTML DOM (Document Object Model). This can be done through the HtmlPage.Document object:
HtmlDocument doc = HtmlPage.Document;
Make certain to first add a reference to the following namespace:
using System.Windows.Browser;
To illustrate this point I will walk you through a demo that will change the background color of your HTML Page when you click a button. To create this demo, follow these steps:
Step 1. Create a new Silverlight Application using Visual Studio 2008.
Step 2. Open up the your Test page (such as SilverlightApplication1TestPage.aspx) and modify the DIV tag surrounding your Silverlight object to have an ID and background color. In addition, set the width and height to be 20% and your Silverlight control to be 50% wide so that the Silverlight control does not overlap the entire background of the HTML page:
<div id="myDIV" style="background:blue;width:20%;height:20%">
<asp:Silverlight ID="Xaml1" runat="server"
Source="~/ClientBin/SilverlightApplication27.xap" MinimumVersion="2.0.30930.0"
Width="50%" Height="100%" />
</div>
Step 3. In Page.xaml add a button with a click event:
<UserControl x:Class="SilverlightApplication1.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Canvas>
<Button Click="Button_Click" Content="Change Colors"></Button>
</Canvas>
</UserControl>
Step 4. In Page.xaml.cs and the following code which will change the background color of your HTML Page. You will notice we are:
- Getting the HTML Document for the page.
- Getting the DIV by it’s ID.
- Setting the style attribute of the DIV changing its background color from its original blue color to green.
private void Button_Click(object sender, RoutedEventArgs e)
{
HtmlDocument doc = HtmlPage.Document;
HtmlElement div = doc.GetElementById("myDIV");
div.SetStyleAttribute("background", "green");
}
Step 5. Run the application. The background of the Silverlight control is white where as the background of the HTML page is blue.
Screen shot before click:
Screen shot after click:
Thank you,
--Mike Snow
Subscribe in a reader