Search code examples
wpfbuttoneventtriggericommand

WPF Commands vs. event trigger commands


In a WPF Button we have a Command parameter which can be binded to ICommand.

<Button Command="{Binding SomeCommand}"/>

We can also use EventTriggers with InvokeCommandAction to fire a ICommand.

<Button>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Click">
            <i:InvokeCommandAction Command="{Binding SomeCommand}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>

What is the difference between them and when to use which?

Update:

I have noticed difference in the following scenario:

  • I have a textbox which validates using IValudationRule if the textbox is empty.
  • I added MultiDataTrigger condition to have the IsEnabled property of a save button to be set to false when the Validation.HasError equals to true.

Using the Button Command all works good, but using the EventTrigger it doesn`t work.

Any reason for this?


Solution

  • Snippets you provide are almost the same,if you don't use CanExecute. InvokeCommandAction is not native WPF class, it is created in Interaction library for the cases when control doesn't provide Command and you have to bind Command to some event. for example when you need command on ListBox.SelectionChanged or etc.

    So based on above, my suggestion is, always use Command if it is possible, and use EventTrigger only when you can't go without it.

    Also Note, than ICommand also provide CanExecute based of which button can enable/disable, which will not work in second case