Partilhar via


BeginAnimation() method for Silverlight

Yeah, it's been awhile since I've blogged anything, so I thought a nice way to get back in the game was to post a BeginAnimation method.  Sometimes you just want to start a simple animation in code, and the Silverlight way of doing it through storyboards just seems like more code that you feel like typing, which is where the WPF-inspired BeginAnimation comes in.  Turns out you can do a pretty good BeginAnimation API yourself, using C# extension methods -- just drop the following code into your project:

    public static class Helper
    {
        public static void BeginAnimation(this FrameworkElement e, string prop, Timeline t)
        {
            var sb = new Storyboard();
            e.Resources.Add(sb);
            sb.Children.Add(t);
            Storyboard.SetTarget(sb, e);
            Storyboard.SetTargetProperty(sb, prop);
            sb.Begin();
        }
    }

Which can be used:
                var tb = (TextBox)sender;
                var an = new DoubleAnimation();
                an.From = 100;
                an.To = 200;
                tb.BeginAnimation("Height", an);
 
(Okay, it doesn't handle all the corner cases quite like WPF, in particular calling BeginAnimation more than once on the timeline doesn't work, and the string parameter will need to change to DependencyProperty in SL beta 2 once we fix the Silverlight Storyboard.TargetProperty signature to match WPF, but the extension method does handle the most common case...)

Comments

  • Anonymous
    May 01, 2008
    sorry for typos :-) ...meant to say: Nick, don't you also want to add an animation completed event handler to remove the resource? Thanks, Lynn

  • Anonymous
    May 01, 2008
    Yeah, it's been awhile since I've blogged anyth

  • Anonymous
    December 05, 2008
    Here's a version of the BeginAnimation extension method, updated for Silverlight 2: static class SilverlightHelpers