Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 861
theSpyCry Avatar asked May 03 '10 07:05

theSpyCry


1 Answers

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>
like image 127
Matt Hamilton Avatar answered Sep 19 '22 20:09

Matt Hamilton