Animation in Silverlight


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 example.

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 article on Silverlight technology.
  1. Silverlight Introduction
  2. Getting started with Silverlight
  3. Data Binding in Silverlight Application
Introduction to Silverlight Animations

Animation in Silverlight is one of the exiting topics which are available since the initial release of the Silverlight technology. There are some enhancements and performance improvement in every release of the Silverlight on Animations. Knowing how to apply Animations in Silverlight applications are very much required because Animations play very important role in most of the applications like gaming, Slideshow etc… Animation gives nice effect to the User interface.

What is Silverlight Animations?

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.

image1.gif

Figure: animation in action in four steps

We can apply the Animation 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 provide the number of classes & objects which help to perform animation in Silverlight applications. Some of the frequently used classes Storyboard, ColorAnimation, DoubleAnimation, PointAnimation and Timeline

image2.gif

Figure: Animation namespace screen shot from MSDN

For more info: http://msdn.microsoft.com/en-us/library/system.windows.media.animation%28v=VS.95%29.aspx

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.

image3.gif


Figure: Animation or Timeline class properties

Here the example of Storyboard class inherited from Timeline abstract class.

image4.gif

What are the Types of Animations in Silverlight?

Animation in Silverlight belongs to two categories:

image5.gif

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 animation. Animations belong to this category are:

    i. ColorAnimation
    ii. DoubleAnimation
    iii. 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 bit complex than basic animations. Animations belongs to this category are:

    i. ColorAnimationUsingKeyFrames
    ii. DoubleAnimationUsingKeyFrames
    iii. 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 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 controls 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.

image6.gif

Figure: Animation controlling storyboard methods

Storyboard Properties

Storybord'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 the 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.

XAML

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 above example, Storyboard class also supports 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 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 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 a 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 by implementing these three steps are 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 discuss 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 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:

image7.gif

Figure: First Animation in Silverlight

What are the important properties/Methods used in the Animation?

All animation classes are inherited from Timline 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.

image8.gif

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 Propertty. 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 secondss because of late BeginTime.

image9.gif

Figure: understand the BegineTime 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();
}

image10.gif

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>

image11.gif

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

image12.gif

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 remain 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 intelligence in Visual Studio 2008

image13.gif

<!--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:

image14.gif

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>

image15.gif

The EventTrigger attaches to the Loaded event o the Grid element and then defines the BeginStoryboard element as part of the TriggerActionCollection.

Example of ColorAnimation

XAML

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

image16.gif

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>

<Button Content="Start" Click="Button_Click" Width="70" Height="30" HorizontalAlignment="Center" />

</StackPanel>

C#

private void Button_Click(object sender, RoutedEventArgs e)
{
    mystoryboard.Begin();
}


image17.gif

Example of PointAnimation

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


image18.gif

Example of Animation with Code behind

XAML

<Canvas x:Name="LayoutRoot" Background="White">

</Canvas>

C#

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

        }
    }

image19.gif

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

image20.gif

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

XAML

<!--Storyboard Methos-->
<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.

Up Next
    Ebook Download
    View all
    Learn
    View all