Tony Vitabile
Tony Vitabile

Reputation: 8614

Trying to add a trigger to a button to change the button's Content property

I've got a UserControl that has a button on it. The UserControl has a DependencyProperty called IsNew. This is a bool value that is set to true if the object being edited in the control was newly created and hasn't been written to the database yet. It is false otherwise.

I've got a button that currently reads "Save". I've been asked to change the button so it reads "Insert" if the row is new. I now have the XAML below for the button:

<Button Background="{DynamicResource ButtonBackground}" 
        Click="SaveButton_Click" 
        Content="Save" 
        FontSize="20" 
        FontWeight="Bold" 
        Foreground="{DynamicResource ButtonForeground}" 
        Height="60"
        IsEnabled="{Binding Path=IsDirty, RelativeSource={RelativeSource AncestorType={x:Type cs:Editor}}}"
        Margin="5"
        Name="SaveButton" 
        TabIndex="7"
        Visibility="{Binding Path=CanModify, Converter={StaticResource BoolToVisibility}}">
    <Button.Triggers>
        <Trigger Property="Editor.IsNew" Value="True">
            <Setter Property="Button.Content" Value="Insert" />
        </Trigger>
        <Trigger Property="Editor.IsNew>
            <Setter Property="Button.Content" Value="Save" />
        </Trigger>
    </Button.Triggers>
</Button>

I'm getting an exception at run time, whose inner exception reads:

Triggers collection members must be of type EventTrigger.

How do I get this to work? I could do this easily in the code-behind, but I want to do it in the XAML.

Thanks

Tony

Upvotes: 4

Views: 29902

Answers (2)

Nikolay
Nikolay

Reputation: 3828

You can use only EventTriggers in Control.Triggers. To use other kind of trigger (Trigger, DataTrigger) you should use style:

<Button.Style>
  <Style TargetType="Button">
    <Style.Triggers>
      <Trigger Property="Editor.IsNew" Value="True">
        <Setter Property="Button.Content" Value="Insert" />
      </Trigger>

And also your Property="Editor.IsNew" and Property="Button.Content" won't work because triggers belongs to Button and trigger will try to find property "Editor.IsNew" on button. You can fix it by changing trigger to DataTrigger and bind with RelativeSource to your UserControl and its IsNew property. And Property="Button.Content" needs to be changed to Property="Content".

Upvotes: 13

NestorArturo
NestorArturo

Reputation: 2516

The reason for this is that a control can only implement EventTriggers. The other kind of triggers you need have to be implemented in a style, and then your button uses that style.

Upvotes: 1

Related Questions