加动画一般在XAML中,但是在某些时刻需要动态得用C#去写动画逻辑。
使用Storyboard.Begin
第一个方法比较简单,比如有这样一个Rectangle已经定义在XAML中:
<Rectangle Name="rectangle" />
我们把Rectangle的颜色从红色变为绿色:
var storyboard = new Storyboard();
Storyboard.SetTarget(storyboard, rectangle);
Storyboard.SetTargetProperty(storyboard, new PropertyPath("Fill.Color"));
var colorAnm = new ColorAnimation(Colors.Red, new Duration(TimeSpan.FromSeconds(1)));
colorAnm.From = Colors.Green;
storyboard.Children.Add(colorAnm);
storyboard.Begin();
注意Storyboard的SetTargetProperty需要一个PropertyPath对象,这里通过这个PropertyPath去指定Fill属性的Color属性。
使用Animatable.BeginAnimation
如果直接使用Animatable.BeginAnimation,那么我们只能使用SolidColorBrush的BeginAnimation方法。由于XAML上直接定义的控件Freezable.IsFrozen为True。所以这种方法,我们只能手动创建需要动画的对象,然后设置自己的没有被封冻(Freezable.IsFrozen=false)的SolidColorBrush,最后使用这个SolidColorBrush的BeginAnimation开始动画。
代码:
var solid = new SolidColorBrush(Colors.Green);
//创建Rectangle
var rec = new Rectangle() { Fill = solid };
//添加Rectangle到界面上
grid.Children.Clear();
grid.Children.Add(rec);
var colorAnm = new ColorAnimation(Colors.Red, new Duration(TimeSpan.FromSeconds(1)));
colorAnm.From = Colors.Green;
solid.BeginAnimation(SolidColorBrush.ColorProperty, colorAnm);