Introduction

This article explains how to create a simple Silverlight control dynamically at runtime with XML binding. I have chosen to discuss a simple example to demonstrate the technique. The technique can, of course, be elaborated as per individual requirements and desires.

Background

In this example, we are changing the storyboard target at runtime to bind the animation as we create the dynamic controls, and are using LINQ to bind the controls with XML.

Using the code

We start by creating a Silverlight project with a simple animation where an image just slides back and forth using Expression Blend. We modify page.xaml with the following code:

Then, we open the XAML in Expression Blend to add the desired animation. In this example, we would add animation to the image so that it slides back and forth. Once done with the animation, Expression Blend generates code and adds a story board to the XAML, with additional code attached to the image as follows:

The highlighted code above is the part that Expression Blend adds in. I am not getting into the details on how the animation was created in Expression Blend as that is beyond the scope of this article. If interested, please feel free to email me at debdatta.dey@gmail.com.

We did the above steps to retrieve the storyboard code from Expression Blend. Next, we can keep the storyboard and remove the controls within the grid so that our code looks like the one below. We will create the controls dynamically from the code-behind now based upon the XML data. After removing the controls, the page.xaml code would look like the code below.

In the following code, we start the storyboard OnMouseEnter of the HyperLinkButton by attaching the target of the storyboard to the image that is within the HyperLinkButton. Additionally, we also make the TextBlock of the HyperLinkButton that gets the mouse event bold. In OnMouseLeave, we set the font weight of the TextBlock back to normal and stop the storyboard.

Points of interest

You might be wondering why I did not use an image followed by a HyperLinkButton versus an image and a TextBlock within the HyperLinkButton control. I chose this primarily because I did not want the underline that would appear when the mouse is rolled over the HyperLinkButton. CSS modifications really do not work. Setting the margin of the HyperLinkButton got rid of the ugly blue box that is created with hyperlinks (margin ="8,-22,143,0" ).