WPF: How to animate color change?

I have a grid window element. I want to apply an animation that changes the background color from white to green in 5 seconds. Here is 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 does not work. Nothing changes. Where am I mistaken? Thank you

+7
source share
2 answers

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 is an explanation:

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

+13
source

Try:

 <ColorAnimation Storyboard.TargetName="PlayButtonArrow" Storyboard.TargetProperty="Fill.Color" From="White" To="Green" Duration="0:0:5.0" AutoReverse="False"/> 
+12
source

All Articles