January 28, 2008
Silverlight AnimationStarting an Animation with Code
The EventTrigger approach is an easy way to kick off an animation. However, in the current build, not all Silverlight events can be used as event triggers. The Loaded event is supported, but mouse-related events like MouseEnter, MouseLeave, and MouseMove are not.
If you want to start an animation in response to these events, you need to interact with the storyboard programmatically. Fortunately, it's easy. The first step is to move your storyboard out of the Triggers collection and place it in another collection of the same element: the Resources collection.
All Silverlight elements provide a Resourcesproperty, which holds a collection where you can store miscellaneous objects. The primary purpose of the Resources collection is to allow you to define objects in XAML that aren't elements, and so can't be placed into the visual layout of your content region. For example, you might want to declare a Brush object as a resource so it can be used by more than one element. Resources can be retrieved in your code or used elsewhere in your markup. Here's an example that defines the rectangle-growing animation as a resource:
<Canvas x:Name="canvas" MouseLeftButtonDown="canvas_Click" ... >
<Canvas.Resources>
<Storyboard x:Name="growStoryboard">
<DoubleAnimation Storyboard.TargetName="rect"
Storyboard.TargetProperty="Width"
Storyboard.TargetName="canvas"
From="160" To="300" Duration="0:0:5"></DoubleAnimation>
</Storyboard>
</Canvas.Triggers>
Rectangle Name="rect" Height="40" Width="160" Fill="Blue"
Canvas.Left="10" Canvas.Top="10"></Rectangle>
Canvas>
Notice that it's now given a name, so you can manipulate it in your code. You'll also notice that you need to explicitly specify the Storyboard.TargetName property to connect it to the right element when you're using this approach.
Now you simply need to call the methods of the Storyboard object in an event handler in your Silverlight code-behind file. The methods you can use include Begin(), Stop(), Pause(), Resume, and Seek(), all of which are fairly self-explanatory.
private void canvas_Click(object o, EventArgs e)
{
growStoryboard.Begin();
}
Configuring Animation Properties
To get the most out of your animations, you need to look a little closer at the base Animation class, which defines the properties that are provided by all animation classes. Table 1 describes them all.
Table 1: Properties of the Animation Class
|
|
||||||||||||||||||||||||||||||||||||||||||||||||
|
|
|
|