我有一个网格,一个窗口根元素。我想应用一个动画,它会在5秒内将背景颜色从白色变为绿色。这是我做的:
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);
}
代码不起作用。什么都没有改变。我哪里弄错了?谢谢。
答案 0 :(得分:15)
解决!
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);
}
以下是解释:
我最初的错误是我想通过为它分配颜色来改变Grid.BackgroundProperty
,但是它接受了画笔而不是苹果和橘子!因此,我创建了一个SolidColorBrush
静态资源,并将其命名为rootElementBrush。在XAML中,我将Grid rootElement
的background属性设置为该静态资源。最后,我修改了动画,现在它改变了SolidColorBrush
的颜色。简单!
答案 1 :(得分:12)
尝试一下:
<ColorAnimation
Storyboard.TargetName="PlayButtonArrow"
Storyboard.TargetProperty="Fill.Color"
From="White"
To="Green"
Duration="0:0:5.0"
AutoReverse="False"/>
答案 2 :(得分:0)
您无需设置StaticResource
,只需使用Storyboard
。
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);
}