Sometimes you might want to create an animation in procedural code (e.g. C#, VB .NET, etc) rather than in XAML like in my previous Animation post. I've seen a lot of traffic on the Silverlight.net forums asking about this subject so in this post I'll just show an example.
The following example shows how to create an animation that animates the Canvas.Top and Canvas.Left attached properties of a rectangle.
// Create a red rectangle that will be the target
// of the animation.
Rectangle myRectangle = new Rectangle();
myRectangle.Width = 200;
myRectangle.Height = 200;
Color myColor = Color.FromArgb(255, 255, 0, 0);
SolidColorBrush myBrush = new SolidColorBrush();
myBrush.Color = myColor;
myRectangle.Fill = myBrush;
// Add the rectangle to the tree.
// Create a duration of 2 seconds.
Duration duration = new Duration(TimeSpan.FromSeconds(0.2));
// Create two DoubleAnimations and set their properties.
DoubleAnimation myDoubleAnimation1 = new DoubleAnimation();
DoubleAnimation myDoubleAnimation2 = new DoubleAnimation();
myDoubleAnimation1.Duration = duration;
myDoubleAnimation2.Duration = duration;
Storyboard sb = new Storyboard();
sb.Duration = duration;
// Set the attached properties of Canvas.Left and Canvas.Top
// to be the target properties of the two respective DoubleAnimations
myDoubleAnimation1.To = 200;
myDoubleAnimation2.To = 200;
// Make the Storyboard a resource.
// Begin the animation.
Notice that you have to use the Storyboard.SetTarget and Storyboard.SetTargetProperty methods to set these respective attached properties rather than the typical syntax used to set properties. Alternate to using SetTarget you can use Storyboard.SetTargetName.
For more detailed information on using Animations in Silverlight see Animation Overview (Silverlight 2).
Programmer Writer - MSFT