How to dynamically create animations from C# in Silverlight
So you want to create an animation from managed code. To do this, there is quite a bit of code needed.
For every animation there needs to be a new StoryBoard, and unfortunately a StoryBoard can not be reused between objects. (Correction: You can reuse a dynamically created StoryBoard. Make sure to call StoryBoard.Stop() before setting the new target.)
The approach we are going to take is to animate the TranslateTransforms instead of animating the Canvas.Top and Canvas.Left properties since this is the preferred way of doing animations in WPF. In the below example we will create a rectangle, attached a set of transforms to the rectangle, and dynamically add animations to the rectangle.
- Create a Rectangle
- Create a function that returns a RenderTransform. (I have added more than the TranslateTransform in case you want to access the other transforms at a later time. It’s good practices to have them there.)
- Create a StoryBoard and add DoubleAnimations for both the X and Y.
- Final product
Come back for part 2 and we’ll animate the Scale and add more than one rectangle.