WPF DoubleAnimationUse the DoubleAnimation element in XAML to animate a Rectangle upon a Canvas element. The Rectangle moves.
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.
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.
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.
Example markup: XAML
Title="MainWindow" Height="350" Width="525"
<Rectangle Name="Rect1" Canvas.Left="10" Fill="LightSeaGreen"
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.
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.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to email@example.com.