Modifying the style of a HTML page from a Silverlight 2 Control
Some time ago I started getting intrested in the remarkable capabilities of Javascript, especially regarding DHTML. It seems pretty useful to be able to modify everything on a HTML page without a round trip to the server to generate a new page.
With this ability in one hand and the powerful graphical and functional properties of Silverlight(and its mini .NET CLR) and System.Windows.Browser namespace in our other hand we are able to modify anything on our hosting page; here's how to do it:
Say you have a ASP.NET page with a Silverlight control hosted by it:
<
div style=" text-align:center">
<asp:Silverlight ID="Xaml1" runat="server" Source="~/ClientBin/DomModifier.xap" MinimumVersion="2.0.30523" PluginBackground="Transparent" Windowless="true"/>
</div>
We want our Silverlight Control to control the color of the Page Body element so, we include 3 sliders for each base color (Red, Green And Blue), all "stacked" up on top of each other:
<StackPanel x:Name="LayoutRoot">
<TextBlock Text="Red" x:Name="redtext"/>
<Slider x:Name="red" Minimum="0" Maximum="255" Value="0" Orientation="Horizontal" Margin ="2" ValueChanged="sliderValueChanged" />
<TextBlock Text="Green" x:Name="greentext"/>
<Slider x:Name="green" Minimum="0" Maximum="255" Value="0" Orientation="Horizontal" Margin ="2" ValueChanged="sliderValueChanged"/>
<TextBlock Text="Blue" x:Name="bluetext"/>
<Slider x:Name="blue" Minimum="0" Maximum="255" Value="0" Orientation="Horizontal" Margin ="2" ValueChanged="sliderValueChanged" />
</StackPanel>

And now to to add some functionality:
First declare somewhere in your Page class
HtmlElement element;
,and then let's get our reference to the page body in the Page() method
element =
HtmlPage.Document.Body;
Alternatively we could get a reference to any object in the HTML DOM by their Id using something like:
element =
HtmlPage.Document.GetElementById("myDiv");
//of course myDiv is the name of the element you want
Finally we need to wire up to the sliderValueChanged event handler
private void sliderValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
element.SetStyleAttribute("background", "#" + Convert.ToInt32(red.Value).ToString("X2") + Convert.ToInt32(green.Value).ToString("X2") + Convert.ToInt32(blue.Value).ToString("X2"));//convert to heXa with 2 leading zeros and build the color from slider values
redtext.Text = Convert.ToInt32(red.Value).ToString("X2");
greentext.Text = Convert.ToInt32(green.Value).ToString("X2");
bluetext.Text = Convert.ToInt32(blue.Value).ToString("X2");//convert to heXa with 2 leading zeros:P
}
And we should have a functional Body background color picker.
Technorati tags: html, dom, style, silverlight