简体   繁体   English

如何通过DataTrigger设置WPF控件的“默认”样式

[英]How to set “default” style of WPF control via DataTrigger

I have a TextBock where I change the style based on a DataTrigger that is triggered via a bound boolean property. 我有一个TextBock,可根据通过绑定的boolean属性触发的DataTrigger更改样式。 What I want is to change the ForeGround color of my text if the value of the bound property is true. 我想要的是如果bound属性的值为true,则更改文本的ForeGround颜色。 If it is false I want to use my "default" style (BodyValueStyle1) again. 如果为假,我想再次使用“默认”样式(BodyValueStyle1)。 How I do it so far is: 到目前为止,我的方法是:

<TextBlock.Style>
    <Style BasedOn="{StaticResource BodyValueStyle1}" TargetType="{x:Type TextBlock}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding IsTrueOrFalse}" Value="True">
                <Setter Property="TextBlock.Foreground" Value="Red"/>
            </DataTrigger>
            <DataTrigger Binding="{Binding IsTrueOrFalse}" Value="False">
                <Setter Property="TextBlock.Foreground" Value="Black"/>
            </DataTrigger>
         </Style.Triggers>
     </Style>
</TextBlock.Style>

It works fine and does what I want, but what I dont like is the following: 它工作正常,可以完成我想要的,但是我不喜欢的是:

<DataTrigger Binding="{Binding IsTrueOrFalse}" Value="False">
    <Setter Property="TextBlock.Foreground" Value="Black"/>
</DataTrigger>

Is there a way to "reset" the style to my default style(BodyValueStyle1) instead of setting all properties that I have changed before at the false condition? 有没有一种方法可以将样式“重置”为我的默认样式(BodyValueStyle1),而不是将我之前更改过的所有属性设置为错误状态? Because my default ForeGround color is black in anyway. 因为我的默认ForeGround颜色仍然是黑色。

If you have a Setter in BodyValueStyle1 : 如果您在BodyValueStyle1有一个Setter BodyValueStyle1

<Setter Property="Foreground" Value="Black" />

Then you can remove the second DataTrigger . 然后,您可以删除第二个DataTrigger The triggers' behavior is already what you would like. 触发器的行为已经是您想要的。

Sources 来源

Another Stack Overflow question with explanation 另一个堆栈溢出问题及其解释

The properties changed by triggers are automatically reset to their previous value when the triggered condition is no longer satisfied. 当不再满足触发条件时,由触发器更改的属性将自动重置为其先前的值。 Triggers are optimized for transient states which are expected to change and return to original state, such as IsPressed on Button and IsSelected on ListBoxItem. 触发器针对预期会改变并返回原始状态的瞬态进行了优化,例如Button上的IsPressed和ListBoxItem上的IsSelected。 The Property of interest must be a dependency property. 感兴趣的属性必须是从属属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM