La documentación de esta respuesta para los demás, ya que hay una manera mucho más simple de hacer esto que pocas veces se hace referencia, y no necesita tocar el XAML en absoluto.
Para vincular un atajo de teclado, en el constructor de Windows simplemente agregue un nuevo enlace de clave a la colección InputBindings. Como comando, pase su clase de comando arbitraria que implementa ICommand. Para el método de ejecución, simplemente implemente la lógica que necesite. En mi ejemplo a continuación, mi clase de WindowCommand toma un delegado que ejecutará siempre que se invoque. Cuando construyo el nuevo WindowCommand para pasar con mi enlace, simplemente indico en mi inicializador, el método que quiero que WindowCommand ejecute.
Puede usar este patrón para crear sus propios atajos rápidos de teclado.
public YourWindow() //inside any WPF Window constructor
{
...
//add this one statement to bind a new keyboard command shortcut
InputBindings.Add(new KeyBinding(//add a new key-binding, and pass in your command object instance which contains the Execute method which WPF will execute
new WindowCommand(this)
{
ExecuteDelegate = TogglePause //REPLACE TogglePause with your method delegate
}, new KeyGesture(Key.P, ModifierKeys.Control)));
...
}
Crea una clase simple de WindowCommand que toma un delegado de ejecución para disparar cualquier método establecido en él.
public class WindowCommand : ICommand
{
private MainWindow _window;
//Set this delegate when you initialize a new object. This is the method the command will execute. You can also change this delegate type if you need to.
public Action ExecuteDelegate { get; set; }
//You don't have to add a parameter that takes a constructor. I've just added one in case I need access to the window directly.
public WindowCommand(MainWindow window)
{
_window = window;
}
//always called before executing the command, mine just always returns true
public bool CanExecute(object parameter)
{
return true; //mine always returns true, yours can use a new CanExecute delegate, or add custom logic to this method instead.
}
public event EventHandler CanExecuteChanged; //i'm not using this, but it's required by the interface
//the important method that executes the actual command logic
public void Execute(object parameter)
{
if (ExecuteDelegate != null)
{
ExecuteDelegate();
}
else
{
throw new InvalidOperationException();
}
}
}
¿Cómo asocio el comando con un elemento de menú? Seguramente esa sería la información más importante para incluir en esta respuesta, pero falta. – Timwi
@Timwi: he utilizado el código anterior de esta manera para agregar un atajo de teclado a un evento existente: RoutedCommand cmndSettings = new RoutedCommand(); cmndSettings.InputGestures.Add (new KeyGesture (Key.S, ModifierKeys.Control)); CommandBindings.Add (nuevo CommandBinding (cmndSettings, mnuSettings_Click)); – itsho
El comentario de itsho hizo que esto funcionara para mí, no podía hacer que el código xml anterior funcionara. – eightx2