1

I have a problem when using ColorAnimationUsingKeyFrames. Briefly:

In Colors.xaml:

<Color x:Key="Color_Main">#ff0000</Color>
<SolidColorBrush x:Key="Brush_Main" Color="{DynamicResource Color_Main}" />

In styles.xaml:

<VisualState x:Name="State_Highlighted">
      <Storyboard>
        <ColorAnimationUsingKeyFrames Storyboard.TargetName="TextTitle" Storyboard.TargetProperty="Foreground.Color">
          <EasingColorKeyFrame KeyTime="0" Value="{StaticResource Color_White}" />
        </ColorAnimationUsingKeyFrames>
      </Storyboard>
</VisualState>

I have multiple buttons that use the Brush_Main brush and the same animation.

I was using:

<SolidColorBrush x:Key="Brush_Main" Color="{StaticResouce Color_Main}" />

instead of:

<SolidColorBrush x:Key="Brush_Main" Color="{DynamicResource Color_Main}" />

and everything was working fine, but I had to switch to DynamicResource as I'm editing the color from code behind at some point.

My problem is, now, whenever I hover over any button of my buttons, all the buttons will do the animation.

Is there any workaround to solve this? I've been looking through the internet for days.

Thanks in advance.

Hoda
  • 31
  • 5
  • You have a problem because you animate the Color of the Brush, which is a shared resource among your brushes. Maybe you could try animating the Brush itself: https://stackoverflow.com/a/29659723/3220898 ? – Arkane Sep 14 '22 at 09:48
  • It's unclear from your example how `Brush_Main` is used in the animation. – mm8 Sep 14 '22 at 12:39

1 Answers1

0

The explanations are long, so I give them not as a comment, as an answer.

SolidColorBrush is Freezable class. When a Freezable instance is created in Resources, WPF tends to freeze that instance. When a property with a value of a frozen Freezable is animated, the animation first creates an unfrozen copy of that instance. And since the copy is animated, and not the instance itself, this does not affect other properties using the same instance.

When you set a Freezable property to a Binding or a DynamicResource, you are declaring that the properties of that instance can be changed at runtime. And if the Freezable properties can change, then WPF will not freeze it, as this will violate the change logic.

Therefore, the animated property will be associated with an unfrozen Freezable instance. And since it is not frozen, the animation will not create a copy of it, but will animate the original instance with which the properties of other elements are associated.

EldHasp
  • 6,079
  • 2
  • 9
  • 24