tags:

views:

322

answers:

2

I want to use some kind of trigger to change a button in my window to IsEnabled = False when the textbox property Validation.HasErrors of my textbox is True.

Can I do this with Triggers of some kind on the Button?

If yes, some example would be nice!

+1  A: 

Yes, you can do this with triggers, but because you are referring to another element, you must use a DataTrigger rather than a normal Trigger:

<Button>
  <Button.Style>
    <Style TargetType="Button">
      <Style.Triggers>
        <DataTrigger Binding="{Binding (Validation.HasError), ElementName=tb}" Value="True">
          <Setter Property="IsEnabled" Value="False" />
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </Button.Style>
</Button>

Note you must use a Style rather than the Button.Triggers collection, because Button.Triggers can contain only EventTriggers.

itowlson
+2  A: 

You can do this by using a Style. If you want to tie it directly to the text box, you could do something like this:

    <Style x:Key="DisabledOnErrors" TargetType="{x:Type Button}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding (Validation.HasErrors)}" Value="True">
                <Setter Property="IsEnabled" Value="False"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>

    <TextBox x:Name="myTextBox" />
    <Button Style="{StaticResource DisabledOnErrors}" 
            DataContext="{Binding ElementName=myTextBox}" />

This works if the button is not already binding to the DataContext for other properties. In this case, the Style is reusable for other button and text box pairings.

Dan Bryant
Is it possible to apply to multiple textboxes for one button?
Tony
You could try using a MultiBinding and a custom IMultiValueConverter. I don't have much experience with these, but the general idea would be to bind the button IsEnabled directly to a MultiBinding that binds to all of the text box (Validation.HasErrors), using the ElementName syntax itowlson showed below. You would then need an IMultiValueConverter that would take a list of bool values and then take the NOT of ORing them all together.
Dan Bryant