简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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