WPF Change Style’s Brush Color

brushesstyleswpf

I have the following styles in WPF to draw and color a box, which is a custom control with various PART_Name items defined in a ResourceDictionary:

<ResourceDictionary>
.
.
.
<Brush x:Key="BoxStroke">#FFD69436</Brush>
  <LinearGradientBrush x:Key="BoxBrush" StartPoint="0,0" EndPoint="0,1">
    <LinearGradientBrush.GradientStops>
      <GradientStop Color="#FAFBE9" Offset="0" />
      <GradientStop Color="Green" Offset="1" />
    </LinearGradientBrush.GradientStops>
  </LinearGradientBrush>

<Style x:Key="BoxStyle" TargetType="Path">
    <Setter Property="Fill" Value="{DynamicResource BoxBrush}"/>
    <Setter Property="Stroke" Value="{DynamicResource BoxStroke}"/>
</Style>

<Style x:Key="Box" TargetType="Path" BasedOn="{StaticResource BoxStyle}">
    <Setter Property="Data" Value="M 0,0 H 60 V40 H 0 Z"/>
</Style>
.
.
.
</ResourceDictionary>

My question is how can I access the GradientStop color property for the brush?

For instance if the user clicks on the box turn it from "Green" to "Blue".

I've got all of the appropriate code to handle user interaction, I am just stumped on how to change the color of the brush.

Best Answer

The easiest way to do this would be to use databinding instead. Bind the view to an object which has a property that contains the value of the colour you want to change. Then bind that property value to the gradient. When the button is clicked, modify that property and the databinding mechanism will update the colour on screen for you. Just make sure you either implement INotifyPropertyChanged or make the property a dependency property.

Good luck!

Related Topic