现在有个需求:
初始状态(未选中)的时候,CheckBox的Content 为 “乒乓球”,然后选中之后,将“乒乓球”就改为“我爱乒乓球” 并且将文字加粗变为红色。
然后就编写代码如下:
<Window.Resources> <Style x:Key="cb" TargetType="{x:Type CheckBox}"> <Setter Property="Foreground" Value="Green"></Setter> <Setter Property="FontSize" Value="20"></Setter> <Style.Triggers> <Trigger Property="IsChecked" Value="True"> <Setter Property="Content" Value="我爱乒乓球"></Setter> <Setter Property="FontWeight" Value="Bold"></Setter> <Setter Property="Foreground" Value="Red"></Setter> </Trigger> </Style.Triggers> </Style> </Window.Resources> <WrapPanel VerticalAlignment="Top" Background="LightBlue"> <CheckBox Content="乒乓球" Style="{StaticResource cb}" Margin="10"></CheckBox> </WrapPanel>
实现效果如下:
奇怪了,为什么文字没有改变呢?
以上问题就是使用触发器初期很容易犯的错误:没有注意样式设置的优先级。
如上案例中:<CheckBox Content="乒乓球" Style="{StaticResource cb}" Margin="10"></CheckBox>
将CheckBox自身的元素标签上设置了Content,这里设置的属性具有最高的优先级,那么元素标签就不会再去使用其他地方设置的属性值,因此无论其他地方如何改变都不会生效。
解决该问题只需要将需要在触发器中需要设置的属性中,将默认值设置到样式内,而不是设置在标签元素自身上。代码如下所示:
<Window.Resources> <Style x:Key="cb" TargetType="{x:Type CheckBox}"> <Setter Property="Foreground" Value="Green"></Setter> <Setter Property="FontSize" Value="20"></Setter> <Setter Property="Content" Value="乒乓球"></Setter> <Style.Triggers> <Trigger Property="IsChecked" Value="True"> <Setter Property="Content" Value="我爱乒乓球"></Setter> <Setter Property="FontWeight" Value="Bold"></Setter> <Setter Property="Foreground" Value="Red"></Setter> </Trigger> </Style.Triggers> </Style> </Window.Resources> <WrapPanel VerticalAlignment="Top" Background="LightBlue"> <CheckBox Style="{StaticResource cb}" Margin="10"></CheckBox> </WrapPanel>