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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

鲤籽鲲   2023-02-03 我要评论

一、问题开始

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

在这里插入图片描述

总结

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们