wpf - Use a backgroundcolor resource for multiple Components correctly


Keywords:wpf 


Question: 

I created a resourcefile in which I want to hold all colors for my application, so that I can change them later, if my boss decides on the colors that he want to have.

My Problem is in the combination of this approach an the usage of a controltemplate for my ComboboxToggleButton. To be precise: if I hover the mouse the combobox, it should change part if its background, which is a GradientBrush.
The current Code (in the VisualstateManager of the ComboBoxToggleButton) looks like this:

<VisualState x:Name="MouseOver">
   <Storyboard>
        <ColorAnimationUsingKeyFrames
           Storyboard.TargetProperty="(Panel.Background).(GradientBrush.GradientStops)[1].(GradientStop.Color)"
           Storyboard.TargetName="Border">
            <EasingColorKeyFrame KeyTime="0" Value="{StaticResource Highlighted_Color}" />
        </ColorAnimationUsingKeyFrames>
   </Storyboard>
</VisualState>

The problem is that this solution changes the color for ALL controls that use the same GradientBrush as a background, not only the color of the control the mouse hovers over.

How can I fix this most easly?

I tryed replacing the Visual States section of the ToggleButton by triggers in the Combobox, but they had no effect.
In the worst case I could go back to the version where the GradientBrush was in every Control directly embedded, so not over a resource from my ColorsAndBrushes file, but that would be rather ugly if I want to change the colors later.


1 Answer: 

When you define something like a GradientBrush, WPF serves up one instance of that object, which is shared by all of the UI controls that reference it. In effect it's a "singleton", so when the animation is applied to the GradientBrush you'll see the effect in all of the other controls simultaneously.

Try adding x:Shared="False" to the GradientBrush. This will ensure that each control using the GradientBrush resource gets its own instance.