Search code examples
wpftexttextboxtriggers

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?


Solution

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