Eclipsed4utoo's Blog
Not Your Ordinary Programmer

WPF – Create Animation Programmatically

This is a short code snippet on creating an animation in WPF through code.

In my Twitter app that I have been working on, I was recently doing some optimizations.  When I first did the app, I was new to WPF and knew nothing about animations.  After spending time in Silverlight, I used that knowledge to do some animations in WPF.

I wanted to do simple “fade-in” and “fade-out” animations when removing tweets from view and adding new tweets to the view.   And being the person that I am, I like doing this stuff in code.  While I like XAML a lot, I still like writing the code.  So here is how to do an animation that changes the Opacity property programmatically.

// because I am doing these as extension methods, they
//   will be available to all UIElement objects, which are
//   basically all controls that can be added to the GUI
public static class ControlAnimationExtensionMethods
{
    public static void FadeIn(this UIElement targetControl)
    {
        DoubleAnimation fadeInAnimation = new DoubleAnimation(0, 1, new Duration(TimeSpan.FromSeconds(1.5)));
        Storyboard.SetTarget(fadeInAnimation, targetControl);
        Storyboard.SetTargetProperty(fadeInAnimation, new PropertyPath(UIElement.OpacityProperty));
        Storyboard sb = new Storyboard();
        sb.Children.Add(fadeInAnimation);
        sb.Begin();
    }

    public static void FadeOut(this UIElement targetControl)
    {
        DoubleAnimation fadeInAnimation = new DoubleAnimation(1, 0, new Duration(TimeSpan.FromSeconds(1.5)));
        Storyboard.SetTarget(fadeInAnimation, targetControl);
        Storyboard.SetTargetProperty(fadeInAnimation, new PropertyPath(UIElement.OpacityProperty));
        Storyboard sb = new Storyboard();
        sb.Children.Add(fadeInAnimation);
        sb.Begin();
    }
}

This code is useful when dynamically creating controls that you want to do animations on.

TextBlock tb = new TextBlock();
tb.Name = "textBlock1";
// set more property values

tb.FadeIn();

Tags: , , ,

Leave a Comment