Animation in-depth with Silverlight 2.0 Beta – Part Two

Published: 16 May 2008
By: Faisal Khan
Download Sample Code

In-Depth analysis of animation with Silverlight 2.0 Beta.

Contents [hide]

Deep dive into Storyboard

I mentioned in the first article that a Storyboard controls animations with a timeline, and provides object and property targeting information for its child animations. This is the cornerstone of Silverlight animation. A Storyboard is a set of one or more animations. It is comparable to a <TransformGroup> element. Storyboard does exactly the same things for animations that <TransformGourp> does for transformations. Storyboard has a Children property that enables you to access all the animation objects within a given Storyboard. Animations do not add or remove elements, they temporarily alter the property values of existing elements. If you create a new Storyboard and add a new rectangle to the canvas, that rectangle will be available to all Storyboards, not just the current one. The rectangle was added to the scene’s base canvas and is not specific to the active Storyboard.

When using Expression Blend to add some animation to your Silverlight application, you’ll find that each scene can have multiple storyboards. Each storyboard is represented as a new timeline in the timelines palette. Storyboards can contain multiple animations, which are treated as a collection of timelines (animations are considered timelines, with interpolation information) with targeting information for each object for which they contain property animations. You can think of a storyboard as a mechanism for organizing and orchestrating all the animations of a particular scene or object. When a timeline is created, it is added as a resource of the containing control which represents that scene. For example, a Storyboard created in the <UserControl.Resources> section can be something like this:

In the above XAML, DoubleAnimation defines the animation. It sets the Storyboard’s TargetName property to Button1. TargetName gets the name of the object whose property it will animate. Storyboard’s TargetProperty has been assigned to Opacity. That means we are going to deal with the Opacity property of the button. The main purpose of the TargetProperty is to get the property of the object to animate. The From property specifies what’s the value the opacity will start at. In this case it is 1.0. If it’s not specified, the animation will start at whatever the property’s current value is. To specifies to what value the animation goes to. This is an optional property because the By property can be used instead. The By property is used to create an animation that changes a value by a set amount, rather than to a specific target. For example, you can create an animation that enlarges a button by 10 units more than its current size.

Duration determines how long the animation will last. In this case it has been fixed to 3 seconds. FillBehavior gets or sets a value that specifies how the animation behaves after it reaches the end of its active period. Ordinarily, FillBehavior is set to HoldEnd, which means that when an animation ends, it continues to apply its final value to the target property. If you change FillBehavior to Stop, as soon as the animation ends the property reverts to its original value. AutoReverse specifies whether the animation reverses back after completion. It’s a Boolean value and if not specified the default is false. With RepeatBehavior you can set how often your animation will repeat itself: something like looping. If it is not set the default is 1 time. If you want your animations to repeat 2 or 3 times you have to assign the RepeatBehavior property 2x or 3x. For example, RepeatBehavior=3x specifies the number of times the animations will repeat. The number of iterations is always followed by the lower-case character x.

To associate a Storyboard with triggers you can use a BeginStoryboard object which is a trigger action that starts a Storyboard. For example, if you want a rectangle to fade in and out of view after it is loaded you can use a BeginStoryboard to trigger the routed event Rectangle.Loaded. Here’s a program that does exactly that:

The Triggers collection is populated by actions. Triggers is one of the two places in the object model where you can place a storyboard for an animation. The other place is as an object in Resources. Currently Triggers can be applied to Canvas, Ellipse, Glyphs, Image, InkPresenter, Line, mediaElement, Path, Polygon, Rectangle and TextBlock. Here is another example of triggers which contains a MediaElement that shows you how a storyboard can be associated with triggers using <BeginStoryboard>, which triggers the action to start a storyboard. You don’t need any procedural code to handle the animation, since the sample is completely declarative. Here’s the XAML:

Listing 1: Page.xaml

I have used here a MediaElement and a TextBlock. The MediaElement uses triggers to wire itself to the routed event MediaElement.Loaded. The <BeginStoryboard> section signals the storyboard to start the animation storyboard that targets a SkewTranform which has been named MediaSkew, and also the property AngleY. Its duration has been set to 30. The TextBlock’s Foreground property has been set to VideoBrush to show you an example of how videos can be applied as foregrounds.

Figure 1: SkewTansform applied to media element

SkewTansform applied to media element

In a scenario where you want to target multiple objects, for example, dynamically change the Storyboard.TargetName property, you can create a program like the following:

Listing 2: Page.xaml

Listing 3: Page.xaml.cs

Figure 2: Targeting Mutiple Objects

Targeting Mutiple Objects

In the above program I have created 4 images which resides under the <StackPanel> section. The Storyborad I’ve created to target multiple objects is in the <Statackpanel.Resources> section. It targets the Opacity property of the 4 images that I’ve created. The duration of this animation is 2 seconds. Also note that the AutoReverse Property has been set to true to reverse the animation after completion and RepeatBehavior is set to Forever for continuous looping. In the code behind I’ve created an event called Start_Animation to control the animation. Here a double animation animates the property Opacity and changes its TargetName to whichever image is clicked.

In this event I’ve first stopped the animation using the Storyboard’s Stop method. Next, to add the same functionality to all the images I’ve assigned Image img=(Image) sender. That means casting sender to Image. After this I’ve called DoubleAnimation’s SetValue method to set the value of TargetName. In this case it is controlStoryboard.SetValue(Storyboard.TargetnameProperty,img.Name). Look at the parameters: it takes a DependencyProperty as the first parameter and an object as the second. If you want to run your animations synchronously you can try the following program to see the effect. The code for this is not complicated by any means. I’ve just added two more Storyboards here and included a Storyboard_Completed event. Here’s the code:

Listing 4: Page.xaml

Listing 5: Page.xaml.cs

Look at the <Storyboard> sections in the XAML. You’ll see that I’ve assigned each storyboard’s completed event to the event I’ve created, which is Storyboard_Completed. If you put emphasis on creating animation procedurally, here’s the basics once again for your convenience.

First, create the instance of the object that you want to target for your animation, in other words the object you want to animate. For example:

After instantiation (here we're using a TextBlock control), set the properties of the. Assume you set the Width and Height of the TextBlock to 300 and 300. Set the Background and Foreground to SolidColorBrush or LinearGradinetBrush or ImageBrush, whatever you like. Set the Text, FontSize as you like. It depends on your taste and requirements. Next add the control to the LayoutRoot - which means add your control to the root element. Assume you’re using Grid as your LayoutRoot. Now declare a new instance of Duration as follows:

Here the duration has been set to 4 seconds. Create an instance of DoubleAnimation and set its duration property to animDuration, the Duration instance we created like so:

Now create an instance of Storyboard and set its duration to animDuration. Again we’re setting the Duration property of the Storyboard to the Duration instance we created previously.

Add the Double animation as the child element of the Storyboard.

Call the Storyboard’s SetTarget method and pass the DoubleAnimation and TextBlock that will be targeted. The SetTarget method takes a Timeline as the first argument and a DependencyObject as the second. In this case tBlockAnimation which is a DoubleAnimation has been passed as Timeline and tBlock which is TextBlock has been passed as a DependencyObject.

Now Call the SetTargetProperty method of Storyboard to target the property. Pass the DoubleAnimation and a string that will represent the targeted object’s property. SetTargetProperty takes a Timeline as the first argument and a string as value. In this case tBlockAnimation which is a DoubleAnimation has been passed as Timeline and TextBlock.FontSize has been passed as string.

Set the To property of the Double animation to more than the FontSize of the TextBlock. For example if you’ve assigned an initial FontSize of 25, you can set the To property of the DoubleAnimation to 40. To makes the font larger, from the size 25 to 40. In this case, I’ve set the To property to 35.

Make the Storyboard a resource. To do this simply add the storyboard to the Resources section of the LayoutRoot, like so:

Begin the Storyboard by calling the Begin method of the Storyboard. If you follow my instruction your completed code should look like the following:

Now wire this to the UserControl’s Loaded event. You’re done. You’ve created procedural animation.

Open Expression Blend and change the Grid’s Background to give your application a nice look. Your XAML should look like the following if you change the background using Expression Blend:

Summary

In the second part of this series, we took a peek at the Storyboard class. You learned how to use it to control how an animation behaves both in space and time. In the next article, we will continue our talk on animations in Silverlight by examining even more features.

About Faisal Khan

Currently working at Vectorform as a Silverlight developer. His passions revolve around creating the next generation desktop application and Rich Internet applications. His goals are to create applications which will serve the user in a friendly and traditional way, but will keep pace with next ge...

View complete profile

Top Articles in this category

WPF Tutorial
With all the new technology that Microsoft is releasing, it's hard to keep up. WPF is one such technology. It is a completely different metaphor for user interface construction than previous frameworks. This article is intended to give a general overview of the key concepts and innovations of WPF, hopefully educating readers enough to make intelligent UI technology decisions and smooth the learning curve for those beginning to work with this framework.

Silverlight "WPF/E" first steps: Getting started with simple analog clock
This article is an introductory article on how to build a WPF/E simple web application that represents an analog clock.

Introduction to XAML Part 1
You are coding in .NET and have basic knowledge of XML. You heard about that Windows Presentation Foundation (a.k.a WPF) and everyone says it’s so cool. Now you want to know more, so let’s get started!

Hello Silverlight : Start your Silverlight journey today!
Start your Silverlight development journey today with this step-by-step article.

Animation in-depth with Silverlight 2.0 Beta – Part One
In-Depth analysis of animation with Silverlight 2.0 Beta.

Top
 
 
 

Please login to rate or to leave a comment.

Product Spotlight