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. These are used with DoubleAnimation
to specify the animation info.
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.
Rectangle
element, and adjust its Fill, Stroke, StrokeThickness
, Width and Height.Rectangle
called Rectangle.Triggers
. This is complicated, but you just have to remember the elements.Loaded
event is triggered on the Window. We use EventTrigger
for this.BeginStoryboard
, we add a Storyboard
element. And in a nested DoubleAnimation
, we specify how the animation occurs.<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>
Program
outputThe rectangle will creep across the window towards the right. It does this in 2 seconds. You can change the Duration to make it slower or faster.
TargetProperty
.TargetProperty
in your XAML. If you do not, an error (a confusing one) will occur.There are other "Animation" elements. Similar to DoubleAnimation
, we can employ DecimalAnimation
to manipulate a floating-point property. ByteAnimation
is similar.
ColorAnimation
can change a color, creating fade effects. These elements can make WPF seem excessively complicated.With WPF, we gain a large set of graphical effects. This is a key advantage of WPF. With Storyboards, we can specify the nature of our animations.