I wanted to bind a CommandBinding
to a ViewModel ICommand
, this way, when the user hits Delete
I can trigger my ViewModel's delete logic.
The only way I know how to do it is in code behind, with this:
<UserControl.CommandBindings>
<CommandBinding Command="ApplicationCommands.Delete" Executed="OnDeleteCommand" />
</UserControl.CommandBindings>
Any MVVM ways of achieving the same?
Here is an example for the delete logic :
One note here:
The delete Button has to reach the DataContext of the ViewModel, so that syntax let us go the DataContext of the Window which in fact is exactly what we want.
ViewModel:
Model:
Delete command:
And the codebehind to set the DataContext:
By sending the ViewModel reference to DeleteCommand we are able to call and send parameters to their methods.
We can choose to delete the item directly from the command:
I think that's about it, you have a working example now.