学无先后,达者为师

网站首页 编程语言 正文

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

作者:鲤籽鲲   更新时间: 2023-03-26 编程语言

一、问题开始

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

在这里插入图片描述

总结

原文链接:https://blog.csdn.net/qq_39847278/article/details/128512228

栏目分类
最近更新