有没有办法在 WPF 中动态更改(和应用)样式?
假设我有在 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
变为绿色。一条线在释放时为粉红色,在选择时为蓝色...现在,我需要更改未选择的属性(粉红色为绿色)...,所以这不仅仅是将其设置为其他颜色,触发器(选择>蓝色) )将不再工作......这可能吗?怎么办?是否可以绑定(bind)到样式中的粉红色,例如绑定(bind)到按钮背景,以反射(reflect)当前使用的样式颜色?
编辑:
对于 1 我尝试过:
Style s = (Style)this.Resources["MyLineStyleKey"];
(s.Setters[0] as Setter).Value = background;
(s.Setters[1] as Setter).Value = background;
但是发生了异常:
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”样式的所有形状的颜色,您可以在代码隐藏中执行以下操作:
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
,则不会出现此行为。
关于wpf - 在 WPF 中动态更改样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3821573/