Suppose your ViewModel provides the New command. You can reassign Application.New binding to VM with such code. In XAML:
<Window.CommandBindings> <CommandBinding Command="New" /> ... </Window.CommandBindings>
Then in the code you can do something like this. (I like to leave the code outside the code, so I put it in the utility class.)
foreach (CommandBinding cb in CommandBindings) { switch (((RoutedUICommand)cb.Command).Name) { case "New": cb.Executed += (sender, e) => ViewModel.New.Execute(e); cb.CanExecute += (sender, e) => e.CanExecute = ViewModel.New.CanExecute(e); break; } }
Anonymous methods provide an exchange between RoutedUICommand and ICommand.
EDIT:. As an alternative, it was considered that it is best to set the binding of commands explicitly using the CommandManager rather than adding handlers.
CommandManager.RegisterClassCommandBinding(typeof(MainWindow), new CommandBinding(ApplicationCommands.New, (sender, e) => ViewModel.NewScore.Execute(e), (sender, e) => e.CanExecute = ViewModel.NewScore.CanExecute(e)));
source share