Silverlight Tip of the Day #76 - Animating objects with DoubleAnimation.
In Silverlight you can use the Storyboard control to animate properties of an object. It can be used against properties of type double, Color or Point. For example, you can animate changing the double type property Opacity of a Rectangle over time. A Storyboard can be declared in your XAML but it must be placed as a resource. For example, the following Storyboard is declared as a resource of the Canvas object:
<Canvas>
<Canvas.Resources>
<Storyboard x:Name="MyRect">
</Storyboard>
</Canvas.Resources>
</Canvas>
The Storyboard control provides the user with two options for animating:
- DoubleAnimation - Uses a From/To direction.
- DoubleAnimationUsingKeyFrames - This is a container for a set of key frames that will determine the value at a given set of points along a time line. We will look at this option in our next tip of the day.
DoubleAnimation.
As stated above, this uses a From/To direction that takes the targeting property from one value to another. Let's take a close look at some of the properties DoubleAnimation provides:
- Storyboard.TargetProperty - Use this to target the property you wish to animate. In should be in the format UIElement.Property.
- Storyboard.TargetName - Use this to target the object you want to animate.
- Duration - Use this property to specify how long the animation should take. Format = [days.]hours:minutes:seconds.
- From/To - The start and end values you want the property to be set to. By Default From = 1.0 and does not have to be set unless you want it to be a different value.
- AutoReverse - This will cause the animation to reverse course once it's completed.
- RepeatBehavior - Set this to "Forever" to cause it to repeat non-stop. You can also set this to a duration (format = [days.]hours:minutes:seconds) or an iteration count.
The following below is an example of a DoubleAnimation where we target an image's opacity fading the image in and out non-stop.
<Canvas>
<Canvas.Resources>
<Storyboard x:Name="CatSB">
<DoubleAnimation Storyboard.TargetName="MyCat" Storyboard.TargetProperty="UIElement.Opacity"
Duration="00:00:02" From="1.0" To="0.0"
AutoReverse="True" RepeatBehavior="Forever">
</DoubleAnimation>
</Storyboard>
</Canvas.Resources>
<Image Source="cat.jpg" x:Name="MyCat" >
</Image>
</Canvas>
To start the Storyboard we call CatSB.Begin(); from our code.
Live Demo:
Thank you,
--Mike Snow
Subscribe in a reader