Andrej Tozon's blog

In the Attic

NAVIGATION - SEARCH

Silverlight 2.0: Creating a basic animation through code

In my previous Silverlight post, I mentioned Silverlight 2.0 API now allows creating animations through code. While this wasn't possible with Silverlight 1.1 Alpha [you would have to create of piece of Xaml, declaring a storyboard with all animations markup, then load it into a Storyboard object by using XamlReader.Load() method], Silverlight 2.0 now makes it pretty easy.

The following animation code will create very basic fade out effect for given element, animating the Opacity property from 1 to 0 in one second:

private DoubleAnimation CreateFadeOutAnimation(string elementName)
{
    DoubleAnimation animation = new DoubleAnimation();
    Storyboard.SetTargetName(animation, elementName);
    Storyboard.SetTargetProperty(animation, "Opacity");
    animation.To = 0;
    animation.Duration = new Duration(TimeSpan.FromSeconds(1));
    return animation;
}
To start this animation, you'll have to add it to a new storyboard first:
Storyboard sb = new Storyboard();
sb.Children.Add(CreateFadeOutAnimation("myElement"));
sb.Duration = new Duration(TimeSpan.FromSeconds(1));
sb.Completed += new EventHandler(sb_Completed);
LayoutRoot.Resources.Add(sb);
sb.Begin();

The "myElement" above is the name of an visual element with this name, which has to exist in the context of the storyboard for it see it. Storyboard is added to the LayoutRoot's resources [LayoutRoot is the name of a default root Grid in Silverlight]. Instead of passing just a name of an element, you could as well pass in the actual element you're animating.

Note the Completed event hookup up there. This is because we want to stop and remove the animation from the resources when animation is done to clean things up a bit. Here's the handler:

void sb_Completed(object sender, EventArgs e)
{
Storyboard sb = (Storyboard)sender; sb.Stop(); this.Resources.Remove(sb); }

That's it. Of course you can add as many animations to the storyboard as you want - animating different elements at the same time, adding different animations, etc... In further posts we might add some more complexity to this basic sample.