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:
- Animatable
- UIElement
- ContentElement
- Visual3D
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:
-
btn.BeginAnimation(Button.FontSizeProperty, ...
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:
-
using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Animation;
class AnimateColorInCode : Window
{
[STAThread]
public static void Main()
{
Application app = new Application();
app.Run(new AnimateColorInCode());
}
public AnimateColorInCode()
{
Title = "Animate Color in Code";
SolidColorBrush brush = new SolidColorBrush(Colors.Red);
Background = brush;
ColorAnimation anima = new ColorAnimation(Colors.Red, Colors.Blue,
new Duration(TimeSpan.FromSeconds(5)));
anima.AutoReverse = true;
anima.RepeatBehavior = RepeatBehavior.Forever;
brush.BeginAnimation(SolidColorBrush.ColorProperty, anima);
}
}
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.