Animate a WPF control and get notified when it’s complete

WPF has some nice features, and Animation has be one of the most interesting. You can easily create a TranslateTransform to move any UIElement around and have it animate smoothly to the destination.

Here is an example of how to completely do this programatically without XAML:

public static void MoveTo(UIElement target, Point from, Point to, TimeSpan speed, Action completed=null)
    TransformGroup grp = new TransformGroup();

    var rotate = new RotateTransform(16);
    var trans = new TranslateTransform();

    target.RenderTransform = grp;

    var aniY = new DoubleAnimation(from.Y, to.Y, speed);
    var aniX = new DoubleAnimation(from.X, to.X, speed);

    if(completed!=null)aniX.Completed += (o, e) => completed();

    trans.BeginAnimation(TranslateTransform.XProperty, aniX);
    trans.BeginAnimation(TranslateTransform.YProperty, aniY); 

The parameters should be self describing, the WPF MoveTo method takes a UIElement (any control basically) and moves it from one position of the screen to another. The speed controls how long it takes to get there, and the completed Action gives you the chance to fire some code when it arrives at the location.

Categories:   Code


Sorry, comments are closed for this item.