Removing the value applied by an animation

August 21, 2008

By default, the final value of an animation will indefinitely apply to the property it is animating.  This is because the default value of an animation’s FillBehavior property is ‘HoldEnd.’  Since only a dependency property (DP) can be animated in WPF, and the DP value resolution algorithm treats an animation’s value as a higher priority source than a local value, if you try to set an animated property to a certain value in code, your value will be ignored.

For example, suppose I want to animate the Height property of a Rectangle element to 200.  I could create the following XAML to accomplish that task:

When that Rectangle is loaded into the UI, it would grow in height from 10 to 200 logical pixels over the course of two seconds.  Since the DoubleAnimation applied to the Height property is using the default FillBehavior, which continues to apply the value 200 to Height after the animation finishes running, setting the element’s Height in code would have no effect.  What I would need to do is remove that animation from the property, so that the value resolution mechanism built into the DP system would use my locally set value.

The trick to removing an animation’s value from a DP is to begin a “null animation” against that property.  This is quite simple to do, as it only requires one method call:

After running those two lines of code, the Rectangle would immediately become 100 logical pixels tall.  UIElement and ContentElement both define the BeginAnimation method, so all elements in WPF have this ability built in.


Good old fashion image animations in WPF

April 23, 2008

As I tried in vain to fall asleep at a reasonable hour tonight, it dawned on me that something is missing from the standard WPF literature. Most of the animation examples show off the awesome built-in support for animations, which means changing a property’s value over time. What I felt was missing is an example of how to create an animation by showing a sequence of images in rapid succession.  Ya know, like Mickey Mouse.  So I got out of bed and made one!

I opened SnagIt, created 37 separate images, saved each one with a name like “001.png”, and then dropped them all into a new project in Visual Studio. All of the image files are copied to the project’s output directory, instead of saving them as resources in the assembly. After assigning the Window’s Content an Image element in XAML, I wrote the following code:

I just love using LINQ!  It makes data processing so much easier.  If you haven’t already done so, I highly recommend you read Joseph Rattz’s “Pro LINQ – Language Integrated Query in C# 2008“.

When I run the app, it looks like this:

If you want the source code, you can download it here. Be sure to change the file extension from .DOC to .ZIP and then decompress the file.