I wish I could define any sort of shortcut like Ctrl + F, Ctrl+P, Ctrl+Alt+Tab to call a method. I tried to use CommandBinding
and KeyBinding
without any success. If I ain't wrong, the only way would use the CanExecute
or Executed
of CommandBinding
to do that, but I didn't know how to associate that with any custom shortcut that I wanted, and it's necessary to define the Command
with, for example, ApplicationCommands.Open
.
It would be perfect if I could simply define the shortcuts like Key="B"
and Modifiers="Control"
with the command Command="SomeEventHandlerHere"
, but it isn't going that simple, unfortunately.
EDIT
I've tried this so far (it looks so wrong even to me):
CommandBinding cb = new CommandBinding(ApplicationCommands.NotACommand, MyMethod);
KeyGesture kg = new KeyGesture(Key.B, ModifierKeys.Control);
KeyBinding kb = new KeyBinding(ApplicationCommands.NotACommand, kg);
this.InputBindings.Add(kb);
private void MyMethod(object sender, ExecutedRoutedEventArgs e)
{
// Do something
}