WPF TextBox 触发器以清除文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2756683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:43:36  来源:igfitidea点击:

WPF TextBox trigger to clear Text

wpftexttextboxtriggers

提问by PaN1C_Showt1Me

I have many TextBoxcontrols and I'm trying to write a style that clears the Textproperty whenthe Control is disabled. I don't want to have Event Handlers in code behind.

我有很多TextBox控件,我正在尝试编写一种样式,禁用控件清除 Text属性。我不想在后面的代码中使用事件处理程序。

I wrote this:

我写了这个:

<Style TargetType="{x:Type TextBox}">                            
 <Style.Triggers>
  <Trigger Property="IsEnabled" Value="False">                                    
   <Setter Property="Text" Value="{x:Null}" />
  </Trigger>                                
 </Style.Triggers>
</Style>

The problem is that if the TextBox is defined like:

问题是,如果 TextBox 被定义为:

<TextBox Text={Binding Whatever} />

then the trigger does not work (probably because it's bound) How to overcome this problem?

那么触发器不起作用(可能是因为它被绑定了)如何克服这个问题?

回答by Matt Hamilton

Because you're explicitly setting the Text in the TextBox, the style's trigger can't overwrite it. Try this:

因为您在 TextBox 中显式设置了 Text,所以样式的触发器不能覆盖它。尝试这个:

<TextBox>
    <TextBox.Style>
        <Style TargetType="{x:Type TextBox}">
            <Setter Property="Text" Value="{Binding Whatever}" />

            <Style.Triggers>
                <Trigger Property="IsEnabled" Value="False">
                    <Setter Property="Text" Value="{x:Null}" /> 
                </Trigger>
            </Style.Triggers>
        </Style> 
    </TextBox.Style>
</TextBox>