开发者

WPF Change Style's Brush Color

开发者 https://www.devze.com 2022-12-10 21:21 出处:网络
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:

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 P开发者_运维技巧roperty="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.


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!


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");
0

精彩评论

暂无评论...
验证码 换一张
取 消