一、问题开始

现在有个需求:
初始状态(未选中)的时候,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>

实现效果如下:

WPF使用触发器需要注意优先级问题解决

奇怪了,为什么文字没有改变呢?

二、问题说明

以上问题就是使用触发器初期很容易犯的错误:没有注意样式设置的优先级。
如上案例中:<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>

WPF使用触发器需要注意优先级问题解决

总结

原文地址:https://blog.csdn.net/qq_39847278/article/details/128512228

相关文章:

  • 2022-02-03
  • 2022-02-13
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-12-05
  • 2021-06-27
  • 2021-09-04
  • 2021-08-15
  • 2021-12-01
  • 2021-06-14
  • 2021-12-11
相关资源
相似解决方案