[XAML data binding]
This example uses storyboard animation to move a rectangle and uses XAML data binding to display the rectangle’s location as it moves. It’s actually fairly simple, at least a far as WPF goes, once you figure out how to do it.




Here’s how the program’s XAML code begins.
This code defines the program’s Window, places a Canvas inside it, and then creates a Rectangle inside that. The code sets some Rectangle properties and then defines a Triggers section.
The Rectangle has a single trigger that executes when the control is loaded. The trigger executes a BeginStoryboard, which contains a Storyboard that repeats indefinitely.
The Storyboard contains three ThicknessAnimation objects that adjust the Rectangle control’s Margin property. The animation objects have BeginTime and Duration properties set so each begins when the previous one ends. The result of the animations is to move the rectangle to the right across the the window, down the right edge, to the left across the bottom, and up along the left edge until the rectangle reaches its starting point.
The following code shows the rest of the program’s XAML.
This code defines three labels, two to display the rectangle’s X and Y coordinates, and one to display a comma in between. The first label sets its Content property to the XAML data binding {Binding ElementName=myRectangle, Path=Margin.Left}. That makes the label display the myRectangle object’s Margin.Top property. When the animations modify the rectangle’s top margin value, this label displays the new value.
The label’s ContentStringFormat property makes the control display the value as an integer. If you don’t set that property, the label displays a ridiculously inappropriate number of digits after the decimal point.
The third label uses XAML data binding similarly to display the rectangle’s Margin.Top value.
That’s all there is to this example. Everything is done in XAML code including the XAML data binding; there’s no code behind. Download the example to experiment with the program.

Download Example   Follow me on Twitter   RSS feed   Donate

source