Search code examples
wpfxamlcoloranimation

Why doens't ColorAnimation work using TargetProperty="Fill"?


I am trying to make a slider control in WPF. So I have an ellipse to change its color to green when it's slided. I tried this code using Storyboard.TargetProperty=Fill

<ColorAnimation Storyboard.TargetName="ball" Storyboard.TargetProperty="Fill.Color" From="Red" To="LightGreen" Duration="0:0:0.3"/>

But it didn't work. I did some research and realized that it needs to be Fill.Color. Normally Ellipse has a Fill property to be filled. Why does it need the Color extension?


Solution

  • Fill is a Brush type not a Color type. There are default converters in place that allow you to use simplified notations such as Fill="Red" in your XAML, but all that means is that you are setting Fill to a SolidColorBrush with a color of Red

    A ColorAnimation as per its name will animate between Colors not Brushes, so you need to get to the Color property of the Fill (in your case fill is a SolidColorBrush which has a Color property).

    As an additional example, if you were to set your Fill to a more complicated Brush such as a LinearGradientBrush, you can still manipulate the gradient in an ColorAnimation but the syntax becomes a lot more complex:

    <ColorAnimation Storyboard.TargetName="ball" 
                    Storyboard.TargetProperty="Fill.(LinearGradientBrush.GradientStops)[1].(GradientStop.Color)"
                    From="Red" To="LightGreen" Duration="0:0:0.3"/>