C# 创建ShortcutKey以调用方法
我希望我可以定义任何类型的快捷方式,如Ctrl+F、Ctrl+p、Ctrl+Alt+Tab来调用方法。我尝试使用C# 创建ShortcutKey以调用方法,c#,wpf,keyboard-shortcuts,C#,Wpf,Keyboard Shortcuts,我希望我可以定义任何类型的快捷方式,如Ctrl+F、Ctrl+p、Ctrl+Alt+Tab来调用方法。我尝试使用CommandBinding和KeyBinding,但没有成功。如果我没有错,唯一的方法就是使用CommandBinding的CanExecute或Executed,但我不知道如何将其与我想要的任何自定义快捷方式相关联,并且有必要将命令定义为,例如,ApplicationCommands.Open 如果我可以用命令command=“SomeEventHandlerHere”简单地定义快
CommandBinding
和KeyBinding
,但没有成功。如果我没有错,唯一的方法就是使用CommandBinding
的CanExecute
或Executed
,但我不知道如何将其与我想要的任何自定义快捷方式相关联,并且有必要将命令定义为,例如,ApplicationCommands.Open
如果我可以用命令command=“SomeEventHandlerHere”
简单地定义快捷方式,如Key=“B”
和Modifiers=“Control”
,那就太完美了,但不幸的是,它没有那么简单
编辑
到目前为止,我已经尝试过了(即使对我来说,它看起来也是错误的):
我刚找到我要找的东西
为了创建我自己的命令(而不是使用预先存在的命令,如“打开”、“帮助”、“保存”等),我需要创建一个新的RoutedUICommand。接下来,我们创建一个CommandBinding来将命令与方法关联起来
<Window.Resources>
<RoutedUICommand x:Key="MyCustomCommand"/>
</Window.Resources>
<Window.CommandBindings>
<CommandBinding Command="{StaticResource MyCustomCommand}" Executed="CommandExecutedMethod" CanExecute="CommandCanExecuteMethod"/>
</Window.CommandBindings>
现在我可以做我想做的事了:
<Window.InputBindings>
<KeyBinding Key="G" Modifiers="Control" Command="{StaticResource MyCustomCommand}"/>
</Window.InputBindings>
字体:
就这么简单。你为什么不发布你迄今为止创建的代码,让我们看看你到底有多接近。看起来你的问题与这个问题非常相似:看起来是同一个问题。但是你能帮我一下吗?:Command=“{x:Static local:MyWindow.MyCommand}
。我收到一个错误:未定义名称空间前缀“local”
。
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>
<Button Content="Click me" Command="{StaticResource MyCustomCommand}" />