MVVM Command Binding: InvokeCommandAction v.s. EventToCommand

时间:2022-01-07 23:18:38

This gives you the ability to create a trigger on an event and bind it to an ICommand on the view model.

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

Assuming the DataContext is your view model, then the above will map the ‘MouseEnter’ event to ‘FooCommand’ on the view model.

The only issue here, is that InvokeCommandAction doesn’t give you the event parameters.

MVVM Light provides the a solution, by offering a different event to command behaviour that can optionally pass the parameters. Like this:

<Button>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseEnter" >
<cmd:EventToCommand Command="{Binding FooCommand}"
PassEventArgsToCommand="True" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>

With this, you’ll find the MouseEventArgs in the Object passed into your command.