Table of Contents
- Overview
- Introduction to Silverlight Animations
- What is Silverlight Animation?
- What is the namespace used in Silverlight Animations?
- Timeline
- What are the Types of Animations in Silverlight?
- Define Animation types
- What is Storyboard?
- Storyboard Properties
- Storyboard Methods
- How to implement the Animation?
- What are the important properties/Methods used in the Animation?
Duration
BeginTime
AutoReverse
RepeatBehavior
FillBe<code>
havior SpeedRatio
- How to trigger the Storyboard Begin event with XAML?
- Example of ColorAnimation
- Example of DoubleAnimation
- Example of PointAnimation
- Example of Animation with Code behind
- Animation in XAML versus Animation in Code
- Start, Stop, Pause, and Resume an Animation
- Conclusion
- History
In this chapter, you will be learning the basic fundamental concepts of Animations in Silverlight Application, which includes Animation Types, namespace details, classes, objects used, implementation of different types of animations with XAML and with C# code and some more interesting samples for each animation. You will see how to use important properties of Timeline
class with examples, controlling animation with storyboard
methods. We will also see Animation in XAML versus Animation in Code with an example.
At the end of this chapter, you will learn:
- Animation basic concepts
- Animation namespace details
- Types of animations like from/to, key-frame and easing functions
- How to implement different types of animations in Silverlight
- Important properties and methods of Storyboard and animation classes
- Animation in XAML versus Animation in Code
- Example for each animation types
You can also find some of my other articles on Silverlight technology:
- Silverlight Introduction - ASilverlightIntroduction.aspx
- Getting started with Silverlight - GettingStartedSilverlight.aspx
- Data Binding in Silverlight - SLDataBindingIntro.aspx
Animation in Silverlight is one of the exciting topics which is available since the initial release of the Silverlight technology. There are some enhancements and performance improvements in every release of Silverlight on Animations. Knowing how to apply Animations in Silverlight applications is very much required because Animations play a very important role in most of the applications like gaming, Slideshow, etc… Animation gives a nice effect to the User interface.
In Silverlight application, we can animate object just by applying their individual properties over the period of time. Here is the simple example of changing Path
property from From="50,450" To="450,50"
within the Canvas 500,500.
Figure: Animation in action in four steps
We can apply the Animation by just changing the height, width, opacity or color of the control. The important thing here to note is we can apply the Animation only on properties whose values are of type double, color and point.
In Silverlight, System.Windows.Media.Animation
namespace provides the number of classes & objects which help to perform animation in Silverlight applications. Some of the frequently used classes are Storyboard
, ColorAnimation
, DoubleAnimation
, PointAnimation
and Timeline
.
Figure: Animation namespace screenshot from MSDN
For more information, visit this link.
All the animation classes are inherited from Timeline abstract
class. Timeline
is the base abstract
class which provides many properties highlighted in the screen which we will be using later in the examples.
Figure: Animation or Timeline class properties
Here the example of Storyboard
class inherited from Timeline abstract
class.
Animation in Silverlight belongs to two categories:
Figure: Type of Animation in Silverlight
- From/To Animation: Animates between a starting and ending value. While creating the Animation, we will be having
From
and To
properties to set the beginning and ending values.
- Use the
From
property to set the starting value - Use the
To
property to set the ending value
These are simple to implement and these are basic animations. Animations belonging to this category are:
ColorAnimation
DoubleAnimation
PointAnimation
- Key-frame Animation: Animates between a series of values specified using key-frame objects. Key-frame animations are more powerful than
From
/To
animations because you can specify any number of target values and even control their interpolation method. This kind of Animation implementation is a bit complex than basic animations. Animations belonging to this category are:
ColorAnimationUsingKeyFrames
DoubleAnimationUsingKeyFrames
PointAnimationUsingKeyFrames
What is ColorAnimation?
Applying the animation on color property of the Silverlight control is known as the ColorAnimation
. For example, a SolidColorBrush
is the color property.
What is ColorAnimationUsingKeyFrames?
Applying the animation on color property of the Silverlight control with more than one value is known as the ColorAnimationUsingKeyFrames
. For example, SolidColorBrush
is the color property.
What is DoubleAnimation?
Applying the animation on integer or double value properties of the Silverlight control is known as the DoubleAnimation
. For example, for example, the Opacity
or Height
or Width
are double or integer value properties.
What is DoubleAnimationUsingKeyFrames?
Applying the animation on integer or double value property of the Silverlight control with more than one value is known as the DoubleAnimationUsingKeyFrames
. For example, Opacity
or Height
or Width
are double or integer value properties.
What is PointAnimation?
Applying the animation on point value properties of the Silverlight control is known as the PointAnimation
. For example, for example, the X, Y coordinates points.
What is PointAnimationUsingKeyFrames?
Applying the animation on point value property of the Silverlight control with more than one value is known as the PointAnimationUsingKeyFrames
. For example, the X, Y coordinates points.
What is ObjectAnimationUsingKeyFrames?
Applying the animation on object related property of the Silverlight control with more than one value is known as the ObjectAnimationUsingKeyFrames
. For example, Fill
property.
Storyboard
class plays a very important role in Silverlight animations. Without using storyboa<code>
rd class, we will not be able to implement the animation in Silverlight. This is the core part of the Animation which acts like the parent control for all Animation controls. This is the container control which contains one or more animation controls like ColorAnimation
, DoubleAnimation
and PointAnimation
, etc… and gives the instruction to Animation controls to play the animation. If you are already familiar with MediaElement
control, you can compare with that control. A storyboard
control has the ability to play, pause, resume and stop the animation.
The Storyboard
class also inherits from Timeline
class. The most important aspects of this class are its methods to begin, stop, pause, and resume the animation.
Figure: Animation controlling storyboard methods
Storyboard
’s TartgetName
and TargetProperty
properties are always required when we define a storyboard
and these two are easy to understand. TargetName
: Use the TargetName
attached property to specify the object to animate. TargetProperty
: Use the TargetProperty
attached property to specify the property to animate.
Let’s take a simple example of how these two properties are used. In this example, I am targeting StackPanel
control to animate. Name of the control MyStackPanel
is assigned to the Storyboard.TargetName
property.
You will notice that assigning Storyboard.TargetProperty
syntax is quite different in this example.
<StackPanel x:Name="myStackPanel" Background="Red" Loaded="Start_Animation">
<StackPanel.Resources>
<Storyboard x:Name="colorStoryboard">
<ColorAnimation BeginTime="00:00:00" Storyboard.TargetName="myStackPanel"
Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)"
From="Red" To="Green" Duration="0:0:4" />
</Storyboard>
</StackPanel.Resources>
</StackPanel>
Notice that the property value being animated (Color
) belongs to a SolidColorBrush
object, which is not named or even explicitly declared. This indirect targeting is accomplished by using the following special syntax.
C#
Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)"
Alternatively, you can explicitly create the SolidColorBrush
, name it, and target its Color
property directly. The following example shows how to create the same animation as the previous example, but using direct property targeting.
<StackPanel Loaded="Start_Animation">
<StackPanel.Resources>
<Storyboard x:Name="colorStoryboard">
<ColorAnimation BeginTime="00:00:00" Storyboard.TargetName="mySolidColorBrush"
Storyboard.TargetProperty="Color" From="Red" To="Green" Duration="0:0:4" />
</Storyboard>
</StackPanel.Resources>
<StackPanel.Background>
<SolidColorBrush x:Name="mySolidColorBrush" Color="Red" />
</StackPanel.Background>
</StackPanel>
Note:
In order to use the TargetName
property in Storyboard
, you need to give the Name
to the target control.
Apart from the properties which we discussed with the above example, Storyboard
class also supports a few methods which we will be using most of the time in the code behind to start, stop, pause and resume.
Begin
: Starts the animation with the first timeline in the storyboard
Pause
: Pauses the current storyboard
's timeline. Call Resume
to unpause the timeline Resume
: Resumes the current storyboard
's timeline Stop
: Stops the animation
Implementing basic animation in Silverlight is very simple and it is just a four step process:
- Create
Object
- Create
Animation
- Define the
Storyboard
- Associate the
Storyb
oard with an event
To discuss the animation implementation, let’s take a simple example and go through step by step.
Step 1: Create Object
In the first step, you need to create a control which you want to animate. In the proceeding example, I have created a simple Ellipse
control and placed it in the Border control so that it will look nice within the border. Make sure that you will be giving the name to the control which you what to change as part of the animation.
<Border x:Name="brdTest" BorderBrush="Green"
BorderThickness="4" Width="400" Height="400">
<Ellipse Width="200" Height="200" >
<Ellipse.Fill>
<SolidColorBrush Color="Yellow" x:Name="myball">
</SolidColorBrush>
</Ellipse.Fill>
</Ellipse>
</Border>
Step 2: Create Animation
Create animation class like ColorAnimation
, DoubleAnimation
, PointAnimation
and set its properties. In the proceeding example, I have created a ColorAnimation
animation and set the required properties. You make sure that you set the required properties like Storyboard.TargetProperty
, Storyboard.TargetName
, From
and To
when you create an Animation
class.
<ColorAnimation
Storyboard.TargetProperty="Color"
Storyboard.TargetName="myball"
From="Yellow"
To="Green" />
Step 3: Define the Storyboard
Animations are implemented in Silverlight through the use of Storyboard
controls that contain one or more child animation controls. The Storyboard
acts similar to a MediaElement
with the ability to play, pause, and stop the animation. When the Storyboard
is played back, the animation controls modify the size, shape, and look of Silverlight controls.
The Storyboard
control acts as a container control for animation controls and allows you to set properties that apply to the animation. The most commonly used properties of the Storyboard
control are AutoReverse
, BeginTime
, RepeatBehavior
, and Duration
.
<StackPanel.Resources>
<Storyboard x:Name="mystoryboard"
AutoReverse="True"
Duration="0:0:5" >
<ColorAnimation
Storyboard.TargetProperty="Color"
Storyboard.TargetName="myball"
From="Yellow"
To="Green" />
</Storyboard>
</StackPanel.Resources>
Note: You have to create Storyboard
control as a resource.
Step 4: Associate the Storyboard with an event
At this movement, you know the controls which you want to animate also created animation controls and defined storyboard for the animation controls. So everything is done, then what is pending? Just implementing these three steps is not sufficient, we also need to have the trigger to start the animation. For this, you need to create a simple button and attach the button click event in the managed code. As we discussed earlier, storyboard control supports Begin()
method to start the animation. By the way, you need to give the Name
to the Storyboard
control so that you will be able to access it in the C# code.
Let’s take a look into the button control and code behind event handler in action.
<Button Content="Start" Click="Button_Click" Width="70" Height="30"
HorizontalAlignment="Center" />
private void Button_Click(object sender, RoutedEventArgs e)
{
mystoryboard.Begin();
}
Wow! We know all steps to create basic animation in Silverlight application. Let’s take a look of all code samples together in one place with output. In this example, the color of the rectangle changed from Yellow to Green.
XAML
<StackPanel>
<StackPanel.Resources>
<Storyboard x:Name="mystoryboard"
AutoReverse="True"
Duration="0:0:5" >
<ColorAnimation
Storyboard.TargetProperty="Color"
Storyboard.TargetName="myball"
From="Yellow"
To="Green" />
</Storyboard>
</StackPanel.Resources>
<Border x:Name="brdTest" BorderBrush="Green" BorderThickness="4"
Width="400" Height="400">
<Ellipse Width="200" Height="200" >
<Ellipse.Fill>
<SolidColorBrush Color="Yellow" x:Name="myball">
</SolidColorBrush>
</Ellipse.Fill>
</Ellipse>
</Border>
<Button Content="Start" Click="Button_Click" Width="70"
Height="30" HorizontalAlignment="Center" />
</StackPanel>
C#
private void Button_Click(object sender, RoutedEventArgs e)
{
mystoryboard.Begin();
}
Output
Figure: First Animation in Silverlight
All animation classes are inherited from Timeline
base class which contains some properties and methods which are available to all animation classes. Let’s talk about the properties of the animation controls before proceeding with examples. I have highlighted some of the most important properties of the Timeline
class below.
Figure: Animation or Timeline class properties
Duration
: The Duration
property allows you to specify the amount of time the Storyboard
will take to play back. The value of Duration
is based on the hours:minutes:seconds
syntax. The Duration can also be specified on each animation control in the Storyboard
instead of the Storyboard
control.
BeginTime
: The BeginTime
property specifies the time, in hours:minutes:seconds
format, in the Storyboard
timeline to begin playback of the animation.
As the name suggests, the BeginTime
property allows you to specify a time at which point the animation object begins activity. For example, you could specify a time of ten seconds on the BeginTime
of a Storyboard
. When you begin the Storyboard
using the Begin
method, the Storyboard
will wait ten seconds and then begin.
Let’s take an example to understand the BeginTime
Property. In this example, the duration is 20 seconds but BeginTime
time is 10 seconds. However, Duration
is 20 seconds it does not animate 20 seconds instead it animates only 10 seconds because of late BeginTime
.
Figure: Understand the BeginTime property
<StackPanel Orientation="Vertical" >
<StackPanel.Resources>
<Storyboard BeginTime="0:0:10" x:Name="sbEllipse1">
<DoubleAnimation
Storyboard.TargetName="myBrush1"
Storyboard.TargetProperty="RadiusX"
From="0" To="1"
Duration="0:0:20"
/>
<DoubleAnimation
Storyboard.TargetName="myBrush1"
Storyboard.TargetProperty="RadiusY"
From="0" To="1"
Duration="0:0:20"
/>
</Storyboard>
</StackPanel.Resources>
<Border x:Name="brdTest1" BorderBrush="Green" BorderThickness="4"
Width="300" Height="400">
<Ellipse Height="100" Width="100">
<Ellipse.Fill>
<RadialGradientBrush x:Name="myBrush1"
RadiusX="0.0"
RadiusY="0.0"
GradientOrigin="0.5,0.5">
<GradientStop Color="Red" Offset="0.25"/>
<GradientStop Color="Green" Offset="0.50"/>
<GradientStop Color="Yellow" Offset="0.75"/>
<GradientStop Color="Blue" Offset="1.0"/>
</RadialGradientBrush>
</Ellipse.Fill>
</Ellipse>
</Border>
<Button Content="Start" Click="Button1_Click" Width="70"
Height="30" HorizontalAlignment="Center" />
</StackPanel>
private void Button1_Click(object sender, RoutedEventArgs e)
{
sbEllipse1.Begin();
}
Figure: Example of BeginTime properties
AutoReverse
: If the AutoReverse
property is set to True
, the animation first plays forward and then immediately plays backward. This allows you to return the Silverlight controls to their original status. This is extremely useful when implementing animations that animate controls only when the mouse is over them.
<StackPanel.Resources>
<Storyboard BeginTime="0:0:0" x:Name="sbEllipse2" AutoReverse="True">
<DoubleAnimation
Storyboard.TargetName="myBrush2"
Storyboard.TargetProperty="RadiusX"
From="0" To="1"
Duration="0:0:10"
/>
<DoubleAnimation
Storyboard.TargetName="myBrush2"
Storyboard.TargetProperty="RadiusY"
From="0" To="1"
Duration="0:0:10"
/>
</Storyboard>
</StackPanel.Resources>
Figure: AutoReverse Property example output
RepeatBehavior
: The RepeatBehavior
property allows you to specify the number of times to repeat the animation. If you want the animation to run indefinitely, you can set the RepeatBehavior
property to Forever
. If AutoReverse
is set to True
, then playing forward and backward only counts as a single iteration. For example, the following Storyboard
code repeats the animation three times:
Basically, a RepeatBehavior can be defined as:
Ø Timespan string RepeatBehavior="0:0:4"
Ø #x string RepeatBehavior="2x"
Ø special value Forever RepeatBehavior="Forever"
Here is the example of how RepeatBehavior
property is used.
<StackPanel>
<StackPanel.Resources>
<Storyboard x:Name="myStoryboard">
<DoubleAnimation
Storyboard.TargetName="ForeverRepeatingRectangle"
Storyboard.TargetProperty="Width"
From="50" To="300" Duration="0:0:2" RepeatBehavior="Forever" />
<DoubleAnimation
Storyboard.TargetName="FourSecondsRepeatingRectangle"
Storyboard.TargetProperty="Width"
From="50" To="300" Duration="0:0:2" RepeatBehavior="0:0:4" />
<DoubleAnimation
Storyboard.TargetName="TwiceRepeatingRectangle"
Storyboard.TargetProperty="Width"
From="50" To="300" Duration="0:0:2" RepeatBehavior="2x" />
<DoubleAnimation
Storyboard.TargetName="HalfRepeatingRectangle"
Storyboard.TargetProperty="Width"
From="50" To="300" Duration="0:0:2" RepeatBehavior="0.5x" />
<DoubleAnimation
Storyboard.TargetName="OneSecondRepeatingRectangle"
Storyboard.TargetProperty="Width"
From="50" To="300" Duration="0:0:2" RepeatBehavior="0:0:1" />
</Storyboard>
</StackPanel.Resources>
<TextBlock Text="RepeatBehavior Property" />
<Border x:Name="brdTest4" BorderBrush="Green" BorderThickness="4"
Width="300" Height="400">
<StackPanel>
<Rectangle Name="ForeverRepeatingRectangle"
Fill="Red" Width="50" Height="20" />
<Rectangle Name="FourSecondsRepeatingRectangle"
Fill="Blue" Width="50" Height="20" />
<Rectangle Name="TwiceRepeatingRectangle"
Fill="Yellow" Width="50" Height="20" />
<Rectangle Name="HalfRepeatingRectangle"
Fill="Green" Width="50" Height="20" />
<Rectangle Name="OneSecondRepeatingRectangle"
Fill="Orange" Width="50" Height="20" />
</StackPanel>
</Border>
<Button Margin="10" Content="Restart Animation" Click="Start_Animation" />
</StackPanel>
private void Start_Animation(object sender, RoutedEventArgs e)
{
myStoryboard.Begin();
}
Figure: RepeatBehavior Property example output
FillBehavior
: The FillBehavior
property specifies how a timeline behaves when it ends. The default value for this property is HoldEnd
, which means that after an animation ends, the object that was animated holds its final value. For example, if you animate the Opacity
property of a Rectangle from 1 to 0 over 2 seconds, the default behavior is for the rectangle to remains at 0 opacity after the 2 seconds elapses. If you set FillBehavior
to Stop
, the opacity of the rectangle reverts to its original value of 1 after the animation ends.
Look at the intellisense in Visual Studio 2008:
<StackPanel>
<TextBlock Text="FillBehavior Property" />
<Border x:Name="brdTest5" BorderBrush="Green"
BorderThickness="4" Width="300" Height="400">
<Rectangle
x:Name="MyAnimatedRectangle"
Width="100"
Height="100"
Fill="Blue">
<Rectangle.Triggers>
<EventTrigger RoutedEvent="Rectangle.Loaded">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetName="MyAnimatedRectangle"
Storyboard.TargetProperty="Opacity"
From="1.0" To="0" Duration="0:0:10" FillBehavior="HoldEnd" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Rectangle.Triggers>
</Rectangle>
</Border>
</StackPanel>
SpeedRatio
: This specifies the rate of time at which the current timeline elapses relative to its parent. The default value is 1.
Let us understand the SpeedRatio
property in detail. If the SpeedRatio
is set to 3, then the animation completes three times faster. If you decrease it, the animation is slowed down (for example, if SpeedRatio
is set to 0.5 then the animation takes twice as long). Although the overall effect is the same as changing the Duration
property of your animation, setting SpeedRatio
makes it easier to control how simultaneous animations overlap.
The following snapshot describes the DoubleAnimation
of the from/to type with the SpeedRatio
property set to 2. This will cause the fade-in effect on the Image1 Image
control to be completed in 0.5 seconds.
<Storyboard x:Name="fadeIn">
<DoubleAnimation From="0" To="1"
Storyboard.TargetName="Image1"
Storyboard.TargetProperty="Opacity"
SpeedRatio="2">
</DoubleAnimation>
</Storyboard>
Default values: If you don’t use any properties in the animation or storyboard, it will use the default value of the properties, it animates just once.
<StackPanel.Resources>
<Storyboard x:Name="sbEllipse1">
<DoubleAnimation
Storyboard.TargetName="myBrush1"
Storyboard.TargetProperty="RadiusX"
From="0" To="1"
/>
<DoubleAnimation
Storyboard.TargetName="myBrush1"
Storyboard.TargetProperty="RadiusY"
From="0" To="1"/>
</Storyboard>
</StackPanel.Resources>
Output of all of the above properties in action:
Figure: Animation properties in action
As you begin to implement animations in your Silverlight applications, you will find that some of them should be started by the managed code. However, some animations should be started as soon as the application is loaded.
Starting the animation when the page is loaded is possible by nesting the Storyboard
control in an EventTrigger
element for the root layout control. The following code shows an example of nesting a Storyboard
control in an EventTrigger
element of a Grid
control:
<Grid x:Name="LayoutRoot" Background="White">
<Grid.Triggers>
<EventTrigger RoutedEvent="Grid.Loaded">
<TriggerActionCollection>
<BeginStoryboard>
<Storyboard AutoReverse="True" RepeatBehavior="Forever">
<PointAnimation To="50,350" Storyboard.TargetName="line4"
Storyboard.TargetProperty="EndPoint" />
</Storyboard>
</BeginStoryboard>
</TriggerActionCollection>
</EventTrigger>
</Grid.Triggers>
<Border x:Name="brdTest" BorderBrush="Green" BorderThickness="4"
Width="400" Height="400">
<Path Stroke="Black" StrokeThickness="1">
<Path.Data>
<GeometryGroup>
<LineGeometry x:Name="line4" StartPoint="100,150"
EndPoint="200,250" />
</GeometryGroup>
</Path.Data>
</Path>
</Border>
</Grid>
The EventTrigger
attaches to the Loaded
event to the Grid
element and then defines the BeginStoryboard
element as part of the TriggerActionCollection</tt />
.
<StackPanel Orientation="Vertical">
<StackPanel.Resources>
<Storyboard x:Name="mystoryboard"
AutoReverse="True"
Duration="0:0:5" >
<ColorAnimation
Storyboard.TargetProperty="Color"
Storyboard.TargetName="myball"
From="Yellow"
To="Green" />
</Storyboard>
</StackPanel.Resources>
<Border x:Name="brdTest" BorderBrush="Green" BorderThickness="4"
Width="400" Height="400">
<Ellipse Width="200" Height="200" >
<Ellipse.Fill>
<SolidColorBrush Color="Yellow" x:Name="myball">
</SolidColorBrush>
</Ellipse.Fill>
</Ellipse>
</Border>
<Button Content="Start" Click="Button_Click" Width="70"
Height="30" HorizontalAlignment="Center" />
</StackPanel>
C#
private void Button_Click(object sender, RoutedEventArgs e)
{
mystoryboard.Begin();
}
XAML
<StackPanel Orientation="Vertical">
<StackPanel.Resources>
<Storyboard BeginTime="0:0:0" x:Name="sbEllipse" Duration="Forever">
<DoubleAnimation
Storyboard.TargetName="myBrush"
Storyboard.TargetProperty="RadiusX"
From="0" To="1"
Duration="0:0:5"
AutoReverse="True" />
<DoubleAnimation
Storyboard.TargetName="myBrush"
Storyboard.TargetProperty="RadiusY"
From="0" To="1"
Duration="0:0:5"
AutoReverse="True" />
</Storyboard>
</StackPanel.Resources>
<Border x:Name="brdTest" BorderBrush="Green" BorderThickness="4"
Width="400" Height="400">
<Ellipse Height="250" Width="250">
<Ellipse.Fill>
<RadialGradientBrush x:Name="myBrush"
RadiusX="0.0"
RadiusY="0.0"
GradientOrigin="0.5,0.8">
<GradientStop Color="Red" Offset="0.0"/>
<GradientStop Color="Blue" Offset="0.25"/>
<GradientStop Color="Yellow" Offset="0.5"/>
<GradientStop Color="Green" Offset="1.0"/>
</RadialGradientBrush>
</Ellipse.Fill>
</Ellipse>
</Border>
<Button Content="Start" Click="Button_Click" Width="70"
Height="30" HorizontalAlignment="Center" />
</StackPanel>
C#
private void Button_Click(object sender, RoutedEventArgs e)
{
sbEllipse.Begin();
}
XAML
<Canvas Width="500" Height="500">
<Canvas.Resources>
<Storyboard x:Name="myStoryboard">
<PointAnimation
Storyboard.TargetProperty="Center"
Storyboard.TargetName="MyAnimatedEllipseGeometry"
Duration="0:0:5"
From="50,450"
To="450,50"
RepeatBehavior="Forever" />
</Storyboard>
</Canvas.Resources>
<Border x:Name="brdTest" BorderBrush="Green" BorderThickness="4"
Width="500" Height="500">
<Path Fill="Red" Loaded="Start_Animation">
<Path.Data>
<EllipseGeometry x:Name="MyAnimatedEllipseGeometry"
Center="200,100" RadiusX="35" RadiusY="35" />
</Path.Data>
</Path>
</Border>
</Canvas>
C#
private void Start_Animation(object sender, RoutedEventArgs e)
{
myStoryboard.Begin();
}
<Canvas x:Name="LayoutRoot" Background="White">
</Canvas>
public partial class AnimationWithCSharp : UserControl
{
public AnimationWithCSharp()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
Ellipse myEllipse = new Ellipse();
myEllipse.Width = 100;
myEllipse.Height = 100;
RadialGradientBrush myrgBrush = new RadialGradientBrush();
Point mypoint = new Point(0.5, 0.5);
myrgBrush.GradientOrigin = mypoint;
myrgBrush.Center = new Point(0.5, 0.5);
myrgBrush.RadiusX = 0.5;
myrgBrush.RadiusY = 0.5;
GradientStop gStop1 = new GradientStop();
gStop1.Color = Colors.Red;
gStop1.Offset = 0.0;
myrgBrush.GradientStops.Add(gStop1);
GradientStop gStop2 = new GradientStop();
gStop2.Color = Color.FromArgb(255, 0, 255, 0);
gStop2.Offset = 0.5;
myrgBrush.GradientStops.Add(gStop2);
GradientStop gStop3 = new GradientStop();
gStop3.Color = Colors.Blue;
gStop3.Offset = 1;
myrgBrush.GradientStops.Add(gStop3);
myEllipse.Fill = myrgBrush;
LayoutRoot.Children.Add(myEllipse);
Duration duration = new Duration(TimeSpan.FromSeconds(5));
DoubleAnimation myDoubleAnimation1 = new DoubleAnimation();
DoubleAnimation myDoubleAnimation2 = new DoubleAnimation();
myDoubleAnimation1.Duration = duration;
myDoubleAnimation2.Duration = duration;
Storyboard sb = new Storyboard();
sb.Duration = duration;
sb.Children.Add(myDoubleAnimation1);
sb.Children.Add(myDoubleAnimation2);
Storyboard.SetTarget(myDoubleAnimation1, myEllipse);
Storyboard.SetTarget(myDoubleAnimation2, myEllipse);
Storyboard.SetTargetProperty
(myDoubleAnimation1, new PropertyPath("(Canvas.Left)"));
Storyboard.SetTargetProperty
(myDoubleAnimation2, new PropertyPath("(Canvas.Top)"));
myDoubleAnimation1.To = 200;
myDoubleAnimation2.To = 200;
LayoutRoot.Resources.Add("unique_id", sb);
sb.Begin();
}
}
It is very important to understand when to use XAML and when to use code behind to implement animation in Silverlight. Keeping performance of the application in mind, we need to play around.
Defining storyboard
and Timeline
in XAML is generally easier to implement and this is the preferred method in most of the cases but sometimes it is time consuming and more work, in that case we may need to implement storyboard and timelines in backend C#/VB.NET code not with XAML.
In the proceeding example, we have to change the opacity of the color of the grid cell when mouse is over the cell. To achieve this requirement, we can use the XAML but we need to write many lines of code to define storyboards and timelines, but with code it is just less than 50 lines.
namespace AnimationSampleCode
{
public partial class AnimationWithCSharp : UserControl
{
public AnimationWithCSharp()
{
InitializeComponent();
LoadColors();
}
private Random _random = new Random((int)DateTime.Now.Ticks);
private TimeSpan _halfSecond = new TimeSpan(0, 0, 0,0, 500);
private void LoadColors()
{
int gridsize = 15;
for (int i = 0; i < gridsize;i++ )
{
gridColors.RowDefinitions.Add(new RowDefinition());
gridColors.ColumnDefinitions.Add(new ColumnDefinition());
}
for (int col = 0; col < gridsize; col++)
{
for (int row = 0; row < gridsize; row++)
{
Rectangle rect = new Rectangle()
{
Margin = new Thickness(2),
Fill = RandomColor(),
Opacity = .05
};
Grid.SetColumn(rect,col);
Grid.SetRow(rect,row);
Storyboard mouseOverAnimation = new Storyboard();
DoubleAnimation newAnim = new DoubleAnimation()
{
To = 10,
Duration = _halfSecond ,
AutoReverse =true
};
mouseOverAnimation.Children.Add(newAnim);
Storyboard.SetTarget(newAnim,rect);
Storyboard.SetTargetProperty(newAnim,new PropertyPath("Opacity"));
rect.MouseEnter += delegate(object sender, MouseEventArgs e)
{
mouseOverAnimation.Begin();
};
gridColors.Children.Add(rect);
}
}
}
private SolidColorBrush RandomColor()
{
byte[] rgb = new byte[3];
_random.NextBytes(rgb);
Color randomColor = Color.FromArgb(255, rgb[0], rgb[1], rgb[2]);
return new SolidColorBrush(randomColor);
}
}
}
Animation must be started with Storyboard’s begin()
method, once animation started you can stop or pause and then a paused animation can be Resumed.
<StackPanel Orientation="Vertical" HorizontalAlignment="Left">
<StackPanel.Resources>
<Storyboard BeginTime="0:0:0" x:Name="sbEllipse" AutoReverse="True" >
<DoubleAnimation
Storyboard.TargetName="myBrush"
Storyboard.TargetProperty="RadiusX"
From="0" To="1"
Duration="0:0:10"
/>
<DoubleAnimation
Storyboard.TargetName="myBrush"
Storyboard.TargetProperty="RadiusY"
From="0" To="1"
Duration="0:0:10"
/>
</Storyboard>
</StackPanel.Resources>
<TextBlock Text="Storyboard Methods" />
<Border x:Name="brdTest" BorderBrush="Green"
BorderThickness="4" Width="300" Height="400">
<Ellipse Height="100" Width="100">
<Ellipse.Fill>
<RadialGradientBrush x:Name="myBrush"
RadiusX="0.5"
RadiusY="0.5"
GradientOrigin="0.5,0.5">
<GradientStop Color="Red" Offset="0.25"/>
<GradientStop Color="Blue" Offset="0.50"/>
<GradientStop Color="Yellow" Offset="0.75"/>
<GradientStop Color="Green" Offset="1.0"/>
</RadialGradientBrush>
</Ellipse.Fill>
</Ellipse>
</Border>
<StackPanel Orientation="Horizontal">
<Button Content="Start" Click="ButtonStart_Click"
Width="70" Height="30" HorizontalAlignment="Center" />
<Button Content="Pause" Click="ButtonPause_Click"
Width="70" Height="30" HorizontalAlignment="Center" />
<Button Content="Resume" Click="ButtonResume_Click"
Width="70" Height="30" HorizontalAlignment="Center" />
<Button Content="Stop" Click="ButtonStop_Click"
Width="70" Height="30" HorizontalAlignment="Center" />
</StackPanel>
</StackPanel>
C#
private void ButtonStart_Click(object sender, RoutedEventArgs e)
{
sbEllipse.Begin();
}
private void ButtonPause_Click(object sender, RoutedEventArgs e)
{
sbEllipse.Pause();
}
private void ButtonResume_Click(object sender, RoutedEventArgs e)
{
sbEllipse.Resume();
}
private void ButtonStop_Click(object sender, RoutedEventArgs e)
{
sbEllipse.Stop();
}
I hope you enjoyed this chapter; please do not forget to write your comments on this chapter, which will help me to improve myself in the future.
- 7th June, 2010: Initial version