日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

WPF使用觸發(fā)器需要注意優(yōu)先級問題解決_C#教程

作者:鯉籽鯤 ? 更新時(shí)間: 2023-03-26 編程語言

一、問題開始

現(xiàn)在有個(gè)需求:
初始狀態(tài)(未選中)的時(shí)候,CheckBox的Content 為 “乒乓球”,然后選中之后,將“乒乓球”就改為“我愛乒乓球” 并且將文字加粗變?yōu)榧t色。
然后就編寫代碼如下:

    <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>

實(shí)現(xiàn)效果如下:

在這里插入圖片描述

奇怪了,為什么文字沒有改變呢?

二、問題說明

以上問題就是使用觸發(fā)器初期很容易犯的錯誤:沒有注意樣式設(shè)置的優(yōu)先級。
如上案例中:<CheckBox Content="乒乓球" Style="{StaticResource cb}" Margin="10"></CheckBox>

將CheckBox自身的元素標(biāo)簽上設(shè)置了Content,這里設(shè)置的屬性具有最高的優(yōu)先級,那么元素標(biāo)簽就不會再去使用其他地方設(shè)置的屬性值,因此無論其他地方如何改變都不會生效。

三、問題訂正

解決該問題只需要將需要在觸發(fā)器中需要設(shè)置的屬性中,將默認(rèn)值設(shè)置到樣式內(nèi),而不是設(shè)置在標(biāo)簽元素自身上。代碼如下所示:

    <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>

在這里插入圖片描述

總結(jié)

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

欄目分類
最近更新