views:

398

answers:

1

Hi ! 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?

+1  A: 

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>
Matt Hamilton
I just wanted to ask. If I'd like to add this to the Control's Resources as a Style (so I wouldn't have to repeat at 100times), would it be possible with something like TemplateBinding, or do I have to write a Custom Control inheriting from TextBox and in the default Template specifiy this Style with TemplateBinding ?
PaN1C_Showt1Me
Just define the style in the Window's Resources section and give it an x:Key. You can then reference it using StaticResource. Look up "WPF styles" on Google - lots of great articles out there.
Matt Hamilton