【发布时间】:2014-04-07 21:33:46
【问题描述】:
我希望我可以定义任何类型的快捷方式,例如 Ctrl + F、Ctrl+P、Ctrl+Alt+Tab 来调用方法。我尝试使用CommandBinding 和KeyBinding 没有任何成功。如果我没记错的话,唯一的方法是使用CommandBinding 的CanExecute 或Executed 来做到这一点,但我不知道如何将它与我想要的任何自定义快捷方式相关联,并且有必要使用例如ApplicationCommands.Open 定义Command。
如果我可以简单地使用命令Command="SomeEventHandlerHere" 定义Key="B" 和Modifiers="Control" 之类的快捷方式,那将是完美的,但不幸的是,它并没有那么简单。
编辑
到目前为止我已经尝试过了(即使对我来说它看起来也很不对劲):
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
}
【问题讨论】:
-
就这么简单。你为什么不发布你到目前为止创建的代码,我们会看看你有多接近。
-
看来确实是同一个问题。但是你能帮我谈谈这条线吗?:
Command="{x:Static local:MyWindow.MyCommand}。我收到一个错误:The namespace prefix "local" is not defined.
标签: c# wpf keyboard-shortcuts