Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

wpf

triggers

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

like image 273
Tony Vitabile Avatar asked Dec 16 '22 02:12

Tony Vitabile


1 Answers

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".

like image 55
Nikolay Avatar answered May 28 '23 13:05

Nikolay