[WPF] Animate Size

/* / Made by Lonami. \ * | 21:00 11-1-2015 | * \ (C) LonamiWebs */ using System; using System.Windows; using System.Windows.Media.Animation; public static class AnimateUtils { /// <summary> /// Animate a given control to a new size /// </summary> /// <param name="control">The control to be animated</param> /// <param name="milliseconds">The time in milliseconds the animation will last</param> /// <param name="newWidth">The new control's width</param> /// <param name="newHeight">The new control's height</param> public static void AnimateSize(FrameworkElement control, double milliseconds, double newWidth, double newHeight) { var widthAnimation = new DoubleAnimation { From = control.Width, To = newWidth, Duration = TimeSpan.FromMilliseconds(milliseconds) }; var heightAnimation = new DoubleAnimation { From = control.Height, To = newHeight, Duration = TimeSpan.FromMilliseconds(milliseconds) }; Storyboard.SetTargetProperty(widthAnimation, new PropertyPath(FrameworkElement.WidthProperty)); Storyboard.SetTarget(widthAnimation, control); Storyboard.SetTargetProperty(heightAnimation, new PropertyPath(FrameworkElement.HeightProperty)); Storyboard.SetTarget(heightAnimation, control); var s = new Storyboard(); s.Children.Add(widthAnimation); s.Children.Add(heightAnimation); s.Begin(); } /// <summary> /// Animate any control's property /// </summary> /// <param name="control">The control to be animated</param> /// <param name="property">The property that will be animated. For example: FrameworkElement.WidthProperty</param> /// <param name="milliseconds">The time in milliseconds the animation will last</param> /// <param name="oldValue">The old control's property value</param> /// <param name="newValue">The new control's property value</param> public static void AnimateProperty(FrameworkElement control, DependencyProperty property, double milliseconds, double oldValue, double newValue) { var animation = new DoubleAnimation { From = oldValue, To = newValue, Duration = TimeSpan.FromMilliseconds(milliseconds) }; Storyboard.SetTargetProperty(animation, new PropertyPath(property)); Storyboard.SetTarget(animation, control); var s = new Storyboard(); s.Children.Add(animation); s.Begin(); } }
A simple code snippet to animate your controls size (or any other property, why not?)

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.