WPF provides builtin support for animations. The WPF animation system makes it very easy to animate controls and other graphical objects. WPF handles the details of redrawing the screen and other details related to animation behind the scenes. In this article we will apply basic animation to a rectanglar object.
In WPF we apply animation to individual properties instead of controls. The property should meet the following requirements for the animation:
- It should be a dependency property
- It should be part of a class that inherits from the dependency object and also inherits the IAnimatable interface.
In the following example we will see how to animate the rectangle so it appears and disappears from view.
First of all we will create a rectangle inside a stackpanel.
<StackPanel Margin="10">
<Rectangle Name="AnimatingRectangle" Width="250" Height="250" Fill="Red">
</Rectangle>
</StackPanel>
Here we will animate the rectangle's opacity property so that the rectangle disappears from the view. As the opacity property is of type double we will use the DoubleAnimation. To specify a starting value, set the "From" property and to specify the ending value set its "To" property. Also specify the "Duration" property to specify how long it takes to go from the starting value to the ending value. So setting it to 20 will make it take 20 seconds to go from the starting value to the ending value. To make the element return into view after it vanishes, set the AutoReverse property of the animation to true.
To apply an animation to an object, you create a Storyboard and use the TargetName and TargetProperty attached properties to specify the object and the property to animate. Once we have associated the animation with an object, we need to associate the Storyboard with an EventTrigger. To do so we include the Event Trigger inside the "Rectangle.Triggers" collection in XAML in the EventTrigger and add a BeginStoryboard.
BeginStoryboard is a trigger action while EventTrigger is a type of Trigger.
<StackPanel Margin="10">
<Rectangle Name="AnimatingRectangle" Width="250" Height="250" Fill="Red">
<Rectangle.Triggers>

Join the conversation! Your thoughts help the community grow.