tags:

views:

600

answers:

2

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.

+2  A: 

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!

OJ
A: 

Once you can access the brush in code, you will just need to assign it a Color value. For example the System.Windows.Media.ColorConverter class will translate hex/web colors into System.Windows.Media.Color values.

Here's a sample, hopefully this is the general idea of what you're asking about:

System.Windows.Media.LinearGradientBrush gb = new System.Windows.Media.LinearGradientBrush();
gb.GradientStops[0].Color = (Color)ColorConverter.ConvertFromString("#FF00FF00");
routeNpingme