TheDeveloperBlog.com


WPF DoubleAnimation

DoubleAnimation. WPF supports animation of elements. To move an element, we can use a canvas and adjust its position within the canvas. We introduce the BeginStoryboard, Storyboard and DoubleAnimation elements.

Canvas

Example. Animation can be implemented with C# code, but in the simplest case this is not necessary. Here I add a Canvas element to the Window. I specify a single Rectangle element, and adjust its Fill, Stroke, StrokeThickness, Width and Height.

Rectangle

Triggers: I add a sub-element to the Rectangle called Rectangle.Triggers. This is complicated, but you just have to remember the elements.

RoutedEvent: The animation begins when the Loaded event is triggered on the Window. We use EventTrigger for this.

In BeginStoryboard, we add a Storyboard element. And in a nested DoubleAnimation, we specify how the animation occurs. We indicate the target element's name, what property it affects, From, To and a Duration.

Based on:

.NET 4.5

Example markup: XAML

<Window x:Class="WpfApplication28.MainWindow"
	xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
	Title="MainWindow" Height="350" Width="525"
	Loaded="Window_Loaded">
    <Canvas Name="Can1">
	<Rectangle Name="Rect1" Canvas.Left="10" Fill="LightSeaGreen"
		   Stroke="Bisque"
		   StrokeThickness="5"
		   Width="100" Height="100">
	    <Rectangle.Triggers>
		<EventTrigger RoutedEvent="Window.Loaded">
		    <BeginStoryboard>
			<Storyboard>
			    <DoubleAnimation
				Storyboard.TargetName="Rect1"
				Storyboard.TargetProperty="(Canvas.Left)"
				From="10" To="100"
				Duration="0:0:2"/>
			</Storyboard>
		    </BeginStoryboard>
		</EventTrigger>
	    </Rectangle.Triggers>
	</Rectangle>
    </Canvas>
</Window>

When this program is executed, the rectangle will creep across the window towards the right. It does this in two seconds. You can change the Duration to make it move slower (use a higher number) or faster (use a lower one).

From, To: We can adjust the "From" and the "To" to change the animation's start and end values. These are used for the TargetProperty.

Property

Syntax: Please add the parentheses around the TargetProperty in your XAML. If you do not, an error (a confusing one) will occur.


Discussion. There are other "Animation" elements. Similar to DoubleAnimation, we can employ DecimalAnimation to manipulate a floating-point property. ByteAnimation is similar. And ColorAnimation can change a color, creating fade effects.

Tip: These elements at first make WPF seem excessively complicated and impenetrable. But when needed, they make programs simpler.


Summary. With WPF, we gain a large set of graphical effects. This is a key advantage of WPF over older technologies such as Windows Forms. With Storyboards, we can specify, declaratively, the nature of our animations.