8

我有一个网格,一个窗口根元素。我想应用一个动画,它会在 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);
}

代码不起作用。什么都没有改变。我在哪里犯错?谢谢。

4

3 回答 3

19

解决了!

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的背景属性设置为该静态资源。最后,我修改了动画,所以现在它改变了那个的颜色SolidColorBrush。简单的!

于 2010-12-30T19:54:30.713 回答
14

试试这个:

<ColorAnimation
Storyboard.TargetName="PlayButtonArrow" 
Storyboard.TargetProperty="Fill.Color"
From="White"
To="Green"              
Duration="0:0:5.0"
AutoReverse="False"/>
于 2010-12-30T19:13:08.293 回答
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);
}
于 2018-10-31T14:44:12.490 回答