【问题标题】:Create ShortcutKey to call a method创建 ShortcutKey 以调用方法
【发布时间】:2014-04-07 21:33:46
【问题描述】:

我希望我可以定义任何类型的快捷方式,例如 Ctrl + FCtrl+PCtrl+Alt+Tab 来调用方法。我尝试使用CommandBindingKeyBinding 没有任何成功。如果我没记错的话,唯一的方法是使用CommandBindingCanExecuteExecuted 来做到这一点,但我不知道如何将它与我想要的任何自定义快捷方式相关联,并且有必要使用例如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
}

【问题讨论】:

  • 就这么简单。你为什么不发布你到目前为止创建的代码,我们会看看你有多接近。
  • 看来你的问题和这个问题很相似:stackoverflow.com/questions/1361350/keyboard-shortcuts-in-wpf
  • 看来确实是同一个问题。但是你能帮我谈谈这条线吗?:Command="{x:Static local:MyWindow.MyCommand}。我收到一个错误:The namespace prefix "local" is not defined.

标签: c# wpf keyboard-shortcuts


【解决方案1】:

我刚刚找到了我要找的东西。

为了创建我自己的命令(而不是使用预先存在的命令,如“打开”、“帮助”、“保存”等),我需要创建一个新的 RoutedUICommand。接下来,我们创建一个 CommandBinding 来将 Command 与方法关联起来。

<Window.Resources>
    <RoutedUICommand x:Key="MyCustomCommand"/>
</Window.Resources>

<Window.CommandBindings>
    <CommandBinding Command="{StaticResource MyCustomCommand}" Executed="CommandExecutedMethod" CanExecute="CommandCanExecuteMethod"/>
</Window.CommandBindings>  

在我们后面的代码中:

private void CommandCanExecuteMethod(object sender, CanExecuteRoutedEventArgs e)
{
    e.CanExecute = true;
    e.Handled = true;
}

private void CommandExecutedMethod(object sender, ExecutedRoutedEventArgs e)
{
    MessageBox.Show("Command executed");
    e.Handled = true;
}  

现在我可以做我想做的事了:

<Window.InputBindings>
    <KeyBinding Key="G" Modifiers="Control" Command="{StaticResource MyCustomCommand}"/>
</Window.InputBindings>

如上,如果窗口获得焦点,当我们按下Ctrl+G时,会调用CommandExecutedMethod方法。

我们也可以这样使用命令:

<Button Content="Click me" Command="{StaticResource MyCustomCommand}" />  

字体: Tech.Pro StackOverflow

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-01
    相关资源
    最近更新 更多