Silverlight offers you four ways to move an object from here to there
From/To Animation
- Linear Key Frame Animation
- Discrete Key Frame Animation
- Spline Key Frame Animation
From - To Animations
(From there to here, from here to there, funny things are everywhere)
From/To animation is the simplest to understand and thus to implement. You create a Storyboard and within that you create a DoubleAnimation object (you use a DoubleAnimation because the value you are going to change is of type Double).
One example of a value you might set would be the location (e.g., Canvas.Left), or you might set the Opacity of an object. In either case, you start at some value (From) and you end up at some other value (To) and you get from one value to the other over a period of time (the duration).
Here are the properties you'll set for your DoubleAnimation
- Name - the name of the Animation object so that you can refer to it from your code
- Duration - the period over which you want the animation to run - make the period short and the animation will run quickly.
- From - the starting value
- To - The ending value
- Storyboard.TargetName - the name of the object to animate
- Storyboard.TargetProperty - the property in the animated object whose value will change
As an example, you can create a simple square, and then move it from its initial position across the Silverlight control using a From/To Double animation by creating a Storyboard in the Canvas.Resource and then obtaining a reference to that Storyboard in the onload event handler in the code-behind and calling Begin on the storyboard.
Scene.xaml
Scene.Xaml.js
if (!window.Animations)
window.Animations = {};
Animations.Scene = function()
{
}
Animations.Scene.prototype =
{
handleLoad: function(plugIn, userContext, rootElement)
{
var storyboard = plugIn.content.FindName("MoveSquareStoryBoard");
storyboard.Begin();
}
}
All of which is pretty straight forward. You can readily see how changing the target property from Canvas.Left to opacity will cause the square to stop sliding across the control and instead cause it to fade out (it would be good programming practice to change the name of the story board to reflect its new purpose; I've intentionally not done so here to show how little must change. I've not even added an opacity property to the square!),
"MoveSquareStoryBoard" >
"Animate" Duration="00:00:02.00"
From = "1" To = ".25"
Storyboard.TargetName="mySquare"
Storyboard.TargetProperty="Opacity" />
"mySquare"
Height="100"
Width="100"
Fill="Blue"
Stroke="Black"
StrokeThickness="3"
Canvas.Left="100"
Canvas.Top ="20"
/>
Note that Opacity is measured from 1 (fully opaque) to 0 (fully transparent) and we move down to .25 (1/4 opaque) which explains why we use a double and not an integer for the animation. The result is a dramatic fading away of the square,
I will describe the key-frame Animations in another Tip of the Day.