Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Animation in Silverlight

0.00/5 (No votes)
9 Jun 2010 2  
In this chapter, you will be learning the 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 ...

Table of Contents

  1. Overview
  2. Introduction to Silverlight Animations
  3. What is Silverlight Animation?
  4. What is the namespace used in Silverlight Animations?
  5. Timeline
  6. What are the Types of Animations in Silverlight?
  7. Define Animation types
  8. What is Storyboard?
  9. Storyboard Properties
  10. Storyboard Methods
  11. How to implement the Animation?
  12. What are the important properties/Methods used in the Animation?
    1. Duration
    2. BeginTime
    3. AutoReverse
    4. RepeatBehavior
    5. FillBehavior
    6. SpeedRatio
  13. How to trigger the Storyboard Begin event with XAML?
  14. Example of ColorAnimation
  15. Example of DoubleAnimation
  16. Example of PointAnimation
  17. Example of Animation with Code behind
  18. Animation in XAML versus Animation in Code
  19. Start, Stop, Pause, and Resume an Animation
  20. Conclusion
  21. History

Overview

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:

  1. Silverlight Introduction - ASilverlightIntroduction.aspx
  2. Getting started with Silverlight - GettingStartedSilverlight.aspx
  3. Data Binding in Silverlight - SLDataBindingIntro.aspx

Introduction to Silverlight Animations

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.

What is Silverlight Animation?

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.

What is the Namespace Used in Silverlight Animations?

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.

image006.jpg
Figure: Animation namespace screenshot from MSDN

For more information, visit this link.

Timeline

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.

What are the Types of Animations in Silverlight?

Animation in Silverlight belongs to two categories:

Figure: Type of Animation in Silverlight
  1. 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:

    1. ColorAnimation
    2. DoubleAnimation
    3. PointAnimation
  2. 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:
    1. ColorAnimationUsingKeyFrames
    2. DoubleAnimationUsingKeyFrames
    3. PointAnimationUsingKeyFrames

Define Animation Types

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.

What is Storyboard?

Storyboard class plays a very important role in Silverlight animations. Without using storyboard 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.

image013.jpg
Figure: Animation controlling storyboard methods

Storyboard Properties

  • 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">
 
      <!-- Animate the background color of the canvas from red to green
        over 4 seconds. -->
      <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">
      <!-- Animate the background color of the canvas 
    from red to green over 4 seconds. -->
      <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.

Storyboard Methods

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

How to Implement the Animation?

Implementing basic animation in Silverlight is very simple and it is just a four step process:

  1. Create Object
  2. Create Animation
  3. Define the Storyboard
  4. Associate the Storyboard 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

What are the Important Properties/Methods Used in the Animation?

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.

<!--RepeatBehavior-->
<StackPanel>
    <StackPanel.Resources>
        <Storyboard x:Name="myStoryboard">
            <!-- Create an animation that repeats indefinitely. -->
            <DoubleAnimation 
              Storyboard.TargetName="ForeverRepeatingRectangle" 
              Storyboard.TargetProperty="Width" 
              From="50" To="300" Duration="0:0:2" RepeatBehavior="Forever" />
 
            <!-- Create an animation that repeats for four seconds. As a result, the
         animation repeats twice. -->
            <DoubleAnimation 
              Storyboard.TargetName="FourSecondsRepeatingRectangle" 
              Storyboard.TargetProperty="Width"
              From="50" To="300" Duration="0:0:2" RepeatBehavior="0:0:4" />
 
            <!-- Create an animation that repeats twice. -->
            <DoubleAnimation 
              Storyboard.TargetName="TwiceRepeatingRectangle" 
              Storyboard.TargetProperty="Width" 
              From="50" To="300" Duration="0:0:2" RepeatBehavior="2x" />
 
            <!-- Create an animation that repeats 0.5 times. The resulting animation
         plays for one second, half of its Duration. It animates from 50 to 150. -->
            <DoubleAnimation 
              Storyboard.TargetName="HalfRepeatingRectangle" 
              Storyboard.TargetProperty="Width" 
              From="50" To="300" Duration="0:0:2" RepeatBehavior="0.5x" />
 
            <!-- Create an animation that repeats for one second. The resulting animation
         plays for one second, half of its Duration. It animates from 50 to 150. -->
            <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>
                    <!-- Create several rectangles to animate. -->
        <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>
    <!-- Create buttons to restart and stop the animations. -->
    </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:

<!--FillBehavior Property-->
<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>
            <!-- Animates the rectangle's opacity. -->
            <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

How to Trigger the Storyboard Begin Event with XAML?

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.

Example of ColorAnimation

<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();
}

Example of DoubleAnimation

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();
}

Example of PointAnimation

XAML

<Canvas Width="500" Height="500">
        <Canvas.Resources>
            <Storyboard x:Name="myStoryboard">
                <!-- Animate the center point of the ellipse from 0 X, 
        500 Y to 500 X, 0 Y over 5 seconds. -->
                <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>
                    <!-- Describes an ellipse. -->
                    <EllipseGeometry x:Name="MyAnimatedEllipseGeometry" 
            Center="200,100" RadiusX="35" RadiusY="35" />
                </Path.Data>
                <!--<Path.Fill>
                    <RadialGradientBrush x:Name="myBrush"
                                          RadiusX="35"
                                          RadiusY="35"
                                         GradientOrigin="0.5,0.5">
                        <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>
                </Path.Fill>-->
            </Path>
        </Border>    
    </Canvas>

C#

private void Start_Animation(object sender, RoutedEventArgs e)
{
    myStoryboard.Begin();
}

Example of Animation with Code Behind

<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)
        {
            //Create Ellipse that will be targeted for animation here
 
            Ellipse myEllipse = new Ellipse();
            myEllipse.Width = 100;
            myEllipse.Height = 100;
 
            //Create the RadialGradientBrush here
            RadialGradientBrush myrgBrush = new RadialGradientBrush();
            Point mypoint = new Point(0.5, 0.5);
            myrgBrush.GradientOrigin = mypoint;//Method 1
            myrgBrush.Center = new Point(0.5, 0.5);//Method 2
            myrgBrush.RadiusX = 0.5;
            myrgBrush.RadiusY = 0.5;
 
            GradientStop gStop1 = new GradientStop();
            gStop1.Color = Colors.Red;//Method 1 
            gStop1.Offset = 0.0;
            myrgBrush.GradientStops.Add(gStop1);
 
            GradientStop gStop2 = new GradientStop();
            gStop2.Color = Color.FromArgb(255, 0, 255, 0);//Method 2
            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;
            // Add the Ellipse to the tree.
            LayoutRoot.Children.Add(myEllipse);
 
            // Create a duration of 5 seconds.
            Duration duration = new Duration(TimeSpan.FromSeconds(5));
 
            // Create two DoubleAnimations and set their properties.
            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);
 
            // Set the attached properties of Canvas.Left and Canvas.Top
            // to be the target properties of the two respective DoubleAnimations.
            Storyboard.SetTargetProperty
        (myDoubleAnimation1, new PropertyPath("(Canvas.Left)"));
            Storyboard.SetTargetProperty
        (myDoubleAnimation2, new PropertyPath("(Canvas.Top)"));
 
            myDoubleAnimation1.To = 200;
            myDoubleAnimation2.To = 200;
            // Make the Storyboard a resource.
            LayoutRoot.Resources.Add("unique_id", sb);
 
            // Begin the animation.
            sb.Begin(); 
        }       
    }

Animation in XAML versus Animation in Code

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();
            
            //Load simple animation using code behind
            //Loaded += new RoutedEventHandler(MainPage_Loaded);
            
            //Calling Load Color Method here
            LoadColors();
        } 
        
        //Declare page level variables
        private Random _random = new Random((int)DateTime.Now.Ticks);
        private TimeSpan _halfSecond = new TimeSpan(0, 0, 0,0,  500);     
 
        private void LoadColors()
        {
            //create grid cells dynamically
            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++)
                {
                    //Create rectangles and add it to grid cells
                    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"));
                    //Event handler
                    rect.MouseEnter += delegate(object sender, MouseEventArgs e)
                    {
                        mouseOverAnimation.Begin();
                    };
 
                    gridColors.Children.Add(rect);
                }
            }
        }
        //Helper function 
        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);
        }
    }
 
   }

Start, Stop, Pause, and Resume an Animation example

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.

<!--Storyboard Methods-->
<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();
}

Conclusion

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.

History

  • 7th June, 2010: Initial version

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here