简体   繁体   English

WPF TextBox触发器清除文本

[英]WPF TextBox trigger to clear Text

I have many TextBox controls and I'm trying to write a style that clears the Text property when the Control is disabled . 我有很多TextBox控件,我正在尝试编写一个样式, 禁用 Control 清除Text属性。 I don't want to have Event Handlers in code behind. 我不希望代码中有事件处理程序。

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? 然后触发器不起作用(可能是因为它的约束)如何克服这个问题?

Because you're explicitly setting the Text in the TextBox, the style's trigger can't overwrite it. 因为您在TextBox中明确设置Text,所以样式的触发器不能覆盖它。 Try this: 试试这个:

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

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

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