WPF: How to animate color change?

Boris picture Boris · Dec 30, 2010 · Viewed 26.2k times · Source

I have a grid, a window root element. I want to apply an animation which would change it's background color from white to green in 5 seconds. Here's what I did:

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);
}

The code doesn't work. Nothing is changing. Where am I making a mistake? Thanks.

Answer

Boris picture Boris · Dec 30, 2010

Solved!

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);
}

Here's an explanation:

My initial mistake was that I wanted to change the Grid.BackgroundProperty by assigning colors to it, but it accepts brushes instead... apples and oranges! So, I created a SolidColorBrush static resource and named it rootElementBrush. In XAML, I set Grid rootElement's background property to that static resource. And finally, I modified the animation, so now it changes the color for that SolidColorBrush. Easy!