在WPF动画编程中,最常用的动画处理方式是DoubleAnimation动画,但是随着你的开发经验越来越多,你会发现,有时候使用这个动画类会很麻烦,因为这个动画是封闭动画,也就是说在动画的时间间隔内,你不能对它做对应依赖属性的赋值操作,这让你很多时候止步于很好的想法。
因为我们要求某个时刻动画能停止,属性能赋值新的值。所以WPF中提供StoryBoard,这个和IOS中StoryBoard概念有点像,故事版嘛,就是一大堆事情放在同一块进行统一处理,例如你对某个对象坐了多个属性的动画,这些动画就可以用一个StoryBoard统一管理,极其方便。下面博主写了一个StoryBoard的动画,描述一个矩形位置移动,相信在你以后的开发当中会经常用到。
1 public partial class Window1 : Window 2 { 3 public Window1() 4 { 5 InitializeComponent(); 6 Loaded += new RoutedEventHandler(Window1_Loaded); 7 } 8 Storyboard _sb = new Storyboard(); 9 Rectangle rect1 = new Rectangle(); 10 11 void Window1_Loaded(object sender, RoutedEventArgs e) 12 { 13 DoubleAnimation da = new DoubleAnimation() 14 { 15 From = 0, 16 To = 300, 17 FillBehavior = FillBehavior.Stop, 18 //AutoReverse = true, 19 //RepeatBehavior = RepeatBehavior.Forever, 20 Duration = TimeSpan.FromSeconds(2) 21 }; 22 DoubleAnimation da1 = new DoubleAnimation() 23 { 24 From = 0, 25 FillBehavior = FillBehavior.Stop, 26 To = 300, 27 //RepeatBehavior = RepeatBehavior.Forever, 28 Duration = TimeSpan.FromSeconds(2) 29 }; 30 Rectangle rect = new Rectangle(); 31 32 rect.Width = rect.Height = 100; 33 rect.Fill = Brushes.Blue; 34 _canvas.Children.Add(rect); 35 36 rect1.Width = rect1.Height = 100; 37 rect1.Fill = Brushes.Red; 38 _canvas.Children.Add(rect1); 39 40 _sb.Children.Add(da); 41 Storyboard.SetTarget(da, rect); 42 Storyboard.SetTargetProperty(da, new PropertyPath(Canvas.LeftProperty)); 43 _sb.Begin(); 44 } 45 /// <summary> 46 /// 开始动画 47 /// </summary> 48 /// <param name="sender"></param> 49 /// <param name="e"></param> 50 private void Button_Click(object sender, RoutedEventArgs e) 51 { 52 bsCopy = _sb.Clone(); 53 bsCopy.Children.Clear(); 54 foreach (var item in _sb.Children) 55 { 56 57 bsCopy.Children.Add(item); 58 Storyboard.SetTarget(item, rect1); 59 Storyboard.SetTargetProperty(item, Storyboard.GetTargetProperty(item)); 60 } 61 bsCopy.FillBehavior = FillBehavior.Stop; 62 bsCopy.Completed += delegate 63 { 64 int a = 3; 65 Canvas.SetLeft(rect1, 100); 66 }; 67 bsCopy.Begin(); 68 } 69 /// <summary> 70 /// 停止动画 71 /// </summary> 72 Storyboard bsCopy; 73 private void Button_Click_1(object sender, RoutedEventArgs e) 74 { 75 bsCopy.Stop(); 76 Canvas.SetLeft(rect1, 100); 77 } 78 }