Color animation does not work

I have a button named "b" whose background I want to change from black to white, but it does not work.

Error:

The animation object "System.Windows.Media.Animation.ColorAnimation" cannot be used to animate the property "Background" because it has the incompatible type "System.Windows.Media.Brush".

My code is:

Dim changeColor As New Animation.ColorAnimation changeColor.From = Colors.Black changeColor.To = Colors.White changeColor.Duration = TimeSpan.FromSeconds(0.2) Animation.Storyboard.SetTarget(changeColor, b) Animation.Storyboard.SetTargetProperty(changeColor, New PropertyPath(BackgroundProperty)) Dim sb As New Animation.Storyboard sb.Children.Add(changeColor) sb.Begin() 

Any ideas?

+4
source share
2 answers

The background is of the Brush type, which cannot be animated using ColorAnimaion. However, SolidColorBrush has the Color property, so you can do something like:

 Storyboard.SetTargetProperty(changeColor, new PropertyPath("Background.Color")); 
+7
source

It is worth noting that the same problem can be solved in XAML using a form expression:

 <ColorAnimation Duration="0:0:0.2" From="Black" To="White" Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)" Storyboard.TargetName="Body" /> 
+19
source

All Articles