Silverlight animated content

Get Microsoft Silverlight

Animating Silverlight control inside the HTML Page

by Taoffi Nassar 23. December 2009 22:27

A Silverlight control can communicate and interact with other HTML elements of the page on which it is placed.

This is done by using the HtmlPage object (namespace System.Windows.Browser)


By using HtmlPage, you can have access to all HTML elements of the current page and be able to get and set many of their properties and attributes, and, accessorily, call DHTML script functions that may be located there.

This means, among other things, that you can get and set style attributes of the HTML element inside which your own Silverlight control is hosted (the DIV element having the id commonly named "silverlightControlHost")


<div id="silverlightControlHost"



This gave me an idea about creating a custom control which would represent this same hosting html DIV element and, through this custom control, interact with the hosting element properties (width, height, location… etc.)

One of the nice features of Silverlight is the Storyboard animations usually used to animate Silverlight controls.

So, what if we try to use a storyboard to animate the Silverlight hosting html element!


Suppose that our animation should move the html host element across the page. From an html viewpoint, this would mean to change its top/left coordinates.

A Silverlight user control doesn’t contain Top / Left properties required to do such a job. So we have to add those properties to our custom control.


I first created an (empty) custom user control:



<UserControl x:Class="SilverHtmlInteraction.HostingDivControl"





    Width="200" Height="200">

    <Grid x:Name="LayoutRoot" Background="White">





The control members:


private HtmlElement m_div        = null;


public HtmlElement Div


       get { return m_div; }

       set { m_div = value; }



The new Left and Top properties


public double Left


       get { return attrib = GetDimension("left", "offsetLeft", 0.0); }

       set { SetDimentionAttribute("left", value); }


public double Top


       get { return attrib = GetDimension("top", "offsetTop", 0.0); }

       set { SetDimentionAttribute("top", value); }






Download the sample code (83.45 kb)