如何创建没有淡入淡出效果的ColorAnimation

时间:2012-10-04 18:28:03

标签: wpf

我想将矩形的背景颜色更改为绿色1秒,然后将其更改为黑色。我想要模拟打开或关闭的灯光 - 我不想淡化颜色。下面的代码执行我想要的操作,除了它从黑色渐变到绿色,反之亦然。我肯定不想在UI线程上睡觉..........

ColorAnimation animation = new ColorAnimation { From = Colors.Black, To = Colors.LightGreen, Duration = new Duration(TimeSpan.FromSeconds(1)), RepeatBehavior= new RepeatBehavior(1), AutoReverse=true };
SolidColorBrush activityLight = new System.Windows.Media.SolidColorBrush(Colors.Black);
ActivityIndicator.Fill = activityLight;
this.RegisterName("activityLight", activityLight);
ActivityStoryboard = new Storyboard();
ActivityStoryboard.Children.Add(animation);
Storyboard.SetTargetName(animation, "activityLight");
Storyboard.SetTargetProperty(animation, new PropertyPath(SolidColorBrush.ColorProperty));

1 个答案:

答案 0 :(得分:2)

您可以使用ColorAnimationUsingKeyFrames

var colorAnimation = new ColorAnimationUsingKeyFrames();
colorAnimation.KeyFrames.Add(
    new DiscreteColorKeyFrame(Colors.Green, TimeSpan.FromSeconds(0d)));
colorAnimation.KeyFrames.Add(
    new DiscreteColorKeyFrame(Colors.Black, TimeSpan.FromSeconds(1d)));

ActivityIndicator.Fill.BeginAnimation(SolidColorBrush.ColorProperty, colorAnimation);