在 WPF 中动态更改样式 [英] Change a style dynamically in WPF
问题描述
有没有办法在 WPF 中动态更改(和应用)样式?
Is there a way to change(and apply) a style dynamically in WPF?
假设我在 XAML 中声明了样式:
Say I have the style declared in XAML:
<Style TargetType="local:MyLine"
x:Key="MyLineStyleKey" x:Name="MyLineStyleName">
<Setter Property="Fill" Value="Pink"/>
<Style.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter Property="Fill" Value="Blue" />
</Trigger>
</Style.Triggers>
</Style>
稍后,我需要更改
Pink
颜色,例如Green
,以及所有样式MyLineStyleKey
变为绿色.释放时一条线是粉红色,选中时为蓝色...现在,我需要更改未选中的属性(粉红色到绿色)...,所以这不仅仅是将其设置为其他颜色,触发器(选择>蓝色)) 将不再起作用......这可能吗?怎么样?
In a moment, I need to change the
Pink
color, to, sayGreen
, and all lines with styleMyLineStyleKey
became Green. A line is Pink when released, and Blue when selected... Now, I needed to change the unselected property(Pink to Green)..., so this is not just setting it to an other color, the trigger (selection>Blue) will not work anymore...Is that possible? How?
是否可以将绑定到样式中的粉红色,例如按钮背景,以反映当前使用的样式颜色?
Is that possible to bind to the Pink color in the Style, say, to a Button background, that will reflect the currently used style color?
对于 1 我试过:
Style s = (Style)this.Resources["MyLineStyleKey"];
(s.Setters[0] as Setter).Value = background;
(s.Setters[1] as Setter).Value = background;
但是发生了异常:
在使用SetterBase"之后(密封),不可修改.
After a 'SetterBase' is in use (sealed), it cannot be modified.
推荐答案
创建画笔作为资源
<SolidColorBrush x:Key="MyFillBrush" Color="Pink" />
并参考你的风格
<Style x:Key="MyShapeStyle" TargetType="Shape">
<Setter Property="Fill" Value="{DynamicResource MyFillBrush}" />
</Style>
...
<!-- Then further down you may use it like this -->
<StackPanel Width="100">
<Rectangle Style="{StaticResource MyShapeStyle}" Height="50" Margin="8" />
<Rectangle Style="{StaticResource MyShapeStyle}" Height="50" Margin="8" />
<Ellipse Style="{StaticResource MyShapeStyle}" Height="50" Margin="8" />
<Button Content="Click to change color" Click="Button_Click" Margin="8" />
</StackPanel>
现在要更改使用MyShapeStyle"样式的所有形状的颜色,您可以从代码隐藏执行以下操作:
Now to change the color of all shapes that use the "MyShapeStyle" style, you can do the following from your code-behind:
private void Button_Click(object sender, RoutedEventArgs e)
{
Random r = new Random();
this.Resources["MyFillBrush"] = new SolidColorBrush(Color.FromArgb(
0xFF,
(byte)r.Next(255),
(byte)r.Next(255),
(byte)r.Next(255)));
}
使这项工作有效的原因是您在样式中使用 DynamicResource
作为画笔引用 - 这告诉 WPF 监视该资源的更改.如果您改用 StaticResource
,则不会出现此行为.
The thing that makes this work is the fact that you use a DynamicResource
for the brush reference in your style - this tells WPF to monitor that resource for changes. If you use a StaticResource
instead, you won't get this behavior.
这篇关于在 WPF 中动态更改样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!