May 19

Creating a new Storyboard dynamically

Posted in Silverlight      Comments Off on Creating a new Storyboard dynamically

In the last day, I”ve found another quirk with the current 1.1 alpha release of Silverlight. Normally, you create an animation with markup code (ie, XAML). However, I wanted to use C# code and wanted to be able to create a new storyboard dynamically. After reading the docs, I thought that I should be able to call the constructor of each of the items used in the animation and then add it to a Canva”s resources collection.

It simply didn”t work out that way. The only way I”ve managed to create the animation dynmically was by loading the XAML dinamically. Since today I”ve seen this being asked in the forums, I though i should put it here.

Here”s some demo code:

  <Rectangle x:Name=”rectangle” Width=”100″ Height=”200″ Fill=”#FFC13131″ />

And then, on the code behind file:

public void Page_Loaded(object o, EventArgs e)
  // Required to initialize variables

   string xaml = “<Storyboard><ColorAnimationUsingKeyFrames BeginTime=”00:00:00″  ”    +    
                           “Storyboard.TargetName=”rectangle” Storyboard.TargetProperty=”(Shape.Fill).” +
                          “(SolidColorBrush.Color)”><SplineColorKeyFrame KeyTime=”00:00:00″ “+
                          “Value=”#FF2C0606″/><SplineColorKeyFrame KeyTime=”00:00:01” “+

   Storyboard anim = (Storyboard)XamlReader.Load(xaml);
    anim.Begin();//run the animation

I guess that there are several problems that need to be fixed before the alpha is ready to be used in real projects…