WPF:如何设置颜色变化的动画?
我有一个网格,一个窗口根元素。我想应用一个动画,将改变它的背景色从白色到绿色在5秒钟。以下是我所做的:WPF:如何设置颜色变化的动画?,wpf,animation,coloranimation,Wpf,Animation,Coloranimation,我有一个网格,一个窗口根元素。我想应用一个动画,将改变它的背景色从白色到绿色在5秒钟。以下是我所做的: private void Window_Loaded(object sender, RoutedEventArgs e) { ColorAnimation animation; animation = new ColorAnimation(); animation.From = Colors.White; animation.To = Colors.Green
private void Window_Loaded(object sender, RoutedEventArgs e)
{
ColorAnimation animation;
animation = new ColorAnimation();
animation.From = Colors.White;
animation.To = Colors.Green;
animation.Duration = new Duration(TimeSpan.FromSeconds(5));
rootElement.BeginAnimation(Grid.BackgroundProperty, animation);
}
代码不起作用。什么都没有改变。我哪里出错了?谢谢 试试看:
<ColorAnimation
Storyboard.TargetName="PlayButtonArrow"
Storyboard.TargetProperty="Fill.Color"
From="White"
To="Green"
Duration="0:0:5.0"
AutoReverse="False"/>
已解决
private void Window_Loaded(object sender, RoutedEventArgs e)
{
SolidColorBrush rootElementBrush;
ColorAnimation animation;
rootElementBrush = this.FindResource("RootElementBrush") as SolidColorBrush;
// Animate the brush
animation = new ColorAnimation();
animation.To = Colors.Green;
animation.Duration = new Duration(TimeSpan.FromSeconds(5));
rootElementBrush.BeginAnimation(SolidColorBrush.ColorProperty, animation);
}
这里有一个解释:
我最初的错误是,我想通过为网格.BackgroundProperty指定颜色来更改它,但它接受画笔。。。苹果和桔子!因此,我创建了一个
SolidColorBrush
静态资源,并将其命名为rootElementBrush。在XAML中,我将网格rootElement
的后台属性设置为该静态资源。最后,我修改了动画,所以现在它更改了SolidColorBrush
的颜色。轻松点 您不需要设置静态资源
,只需使用情节提要
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// Animate the brush
ColorAnimation animation = new ColorAnimation();
animation.To = Colors.Green;
animation.Duration = new Duration(TimeSpan.FromSeconds(5));
Storyboard.SetTargetProperty(animation, new PropertyPath("(Grid.Background).(SolidColorBrush.Color)", null));
Storyboard storyboard = new Storyboard();
storyboard.Children.Add(animation);
storyboard.Begin(rootElement);
}
我需要它在代码隐藏中,也需要从代码隐藏中调用它。我想我可能在代码中犯了错误,因为我正在尝试更改颜色,但
Grid.Background
属性实际上正在使用笔刷…很高兴您能够解决此问题。您应该选择您自己的答案作为您在这里接受的答案。@zedo我知道,但它告诉我,在接下来的两天内,我将无法将其标记为正确答案。它正在等待事情先冷却下来,哈哈哈如何将“白色”设置为“原始图像颜色”?