Search code examples
c#wpfxamlanimationcoloranimation

Why are WPF animation applied to all Controls of same type?


I'm currently trying to animate some Border element in my WPF application.

I need to change Background property and I'm using ColorAnimation class with this helper method:

public static void AnimateColor(SolidColorBrush to, Animatable fe)
{
    ColorAnimation ca = new()
    {
        To = to.Color,
        Duration = new(TimeSpan.FromSeconds(0.5)),
    };
    fe.BeginAnimation(SolidColorBrush.ColorProperty, ca);
}

And I use the method as follow:

AnimateColor(new SolidColorBrush(Colors.Red), target.Background);

target is the control I want to animate.

However, when I run the code, all instances of the same control type are animated, e.g. all my Border elements in current Window are being animated.

What am I missing here? How do I animate a single instance of Control from code-behind?

Thanks in advance for any help.

Edit, solved by accepted answer

I'm updating my answer so that anyone who is stuck with this "issue" could understand it by first understanding how WPF handle animations.

As suggested by accepted answer, I was setting an initial value to each border background as follow:

SolidColorBrush initialBackground = new(Colors.White);
border1.Background = initialBackground; 
border2.Background = initialBackground; 
border3.Background = initialBackground;

I thought an animation would work on the Control, but this was my error. Now I understood than a WPF ColorAnimation works on the specific value assigned to the DependecyProperty being animated, so in my case, I was animating always the same instance initialBackground.


Solution

  • The controls use a single shared Background Brush, of which you animate the Color property.

    Assign a separate SolidColorBrush to each control that should be animated:

    <Border x:Name="target">
        <Border.Background>
            <SolidColorBrush Color="White"/>
        </Border.Background>
    </Border>