Charles Petzold

WPF Animations in Code without Storyboards

Septermber 26, 2007
New York, N.Y.

In XAML, you define animations in storyboards. You can also use storyboards in code, but they're rather messy and in most cases completely unnecessary.

I mention this because many questioners (and even some answerers) in the MSDN WPF Forum seem to be unaware of the very powerful and very easy BeginAnimation method. You can't use BeginAnimation in XAML, but it's definitely the way to go when you're defining and triggering animations in code.

The following WPF classes define a BeginAnimation method:

These base classes account for quite a large chunk of WPF!

You call BeginAnimation on the object that has the property you want to animate. The first argument to BeginAnimation is the fully-qualified named of the dependency property to animate. For example, suppose you have a Button named btn and you want to animate the FontSize property. You call:

Of course, the Button class inherits the FontSize property and FontSizeProperty dependency property from Control.

The only other required argument to BeginAnimation is an object of type AnimationTimeline, which is a parent class to DoubleAnimation (which you'd probably use in this example) and all the other animation classes. These classes also have a Completed event if you want to be notified when the animation has completed. (This seems to be something else that questioners in the WPF Forum seem to need.)

Here's a complete program that animates the background color of a window:

Of course, you can also use BeginAnimation in any class you write that derives from one of the classes I've listed above. You really just need to back the property with a dependency property. This is why you should be very skeptical about anyone who indicates that dependency properties aren't a big deal in WPF programming.