WPF的快捷键热键是什么?

4

我用UserControl来开发我的应用程序,现在需要为应用程序添加快捷键。我放置了以下代码,但是并没有起作用。请问有什么建议?

我的XAML代码:

<Button  Name="ucBtnUpload" ToolTip="Upload F2" Cursor="Hand" Click="ucBtnUpload_Click" KeyUp="ucBtnUpload_KeyUp_1" >

我的代码后端

private void ucBtnUpload_KeyUp_1(object sender, KeyEventArgs e)
{
if (e.Key == Key.F2)
            {

                Test opj = new Test();
                opj.ShowDialog();

             }
}

你的处理程序是否被触发?你在XAML中正确地连接了事件吗?<ucBtnUpload ... OnClick="ucBtnUpload_KeyUp_1"...> - Geoff James
<Button Name="ucBtnUpload" ToolTip="Upload F2" Cursor="Hand" Click="ucBtnUpload_Click" KeyUp="ucBtnUpload_KeyUp_1" > - RKT
2
你确定要在按钮上触发一个键盘事件吗?这需要该按钮处于焦点状态... - lokusking
3
通常在WPF中,你会通过InputBindings和commands来完成这个操作,而不是拦截键盘事件并处理它们。 - Joey
是的,当我使用示例应用程序时,它也可以正常工作,但是当我将其用于我的项目时,什么都不会发生。这就是为什么我提到我在我的应用程序中使用了用户控件。 - RKT
这个回答解决了你的问题吗?WPF中的键盘快捷键 - StayOnTarget
2个回答

5

你需要尝试类似于这样的东西

private void AddHotKeys()
{
        try
        {
            RoutedCommand firstSettings = new RoutedCommand();
            firstSettings.InputGestures.Add(new KeyGesture(Key.A, ModifierKeys.Alt));
            CommandBindings.Add(new CommandBinding(firstSettings , My_first_event_handler));

            RoutedCommand secondSettings = new RoutedCommand();
            secondSettings.InputGestures.Add(new KeyGesture(Key.B, ModifierKeys.Alt));
            CommandBindings.Add(new CommandBinding(secondSettings , My_second_event_handler));
        }
        catch (Exception err)
        {
            //handle exception error
        }
}

事件

private void My_first_event_handler(object sender, ExecutedRoutedEventArgs e) 
{
      //handler code goes here.
      MessageBox.Show("Alt+A key pressed");
}

private void My_second_event_handler(object sender, RoutedEventArgs e) 
{
     //handler code goes here. 
     MessageBox.Show("Alt+B key pressed");
}

如果您正在遵循MVVM模式,可以尝试这个参考链接
<UserControl.InputBindings>
<KeyBinding Modifiers="Control" 
            Key="E" 
            Command="{input:CommandBinding EditCommand}"/>

查看参考资料
MSDN添加键绑定


0

你应该能够在你的XAML中完成这个操作

<Window.InputBindings>
    <KeyBinding Command="{Binding MyCommand}" Key="F2"/>
</Window.InputBindings>

<Button Command="{Binding MyCommand}"/>

MyCommand是在你的Windows /视图的ViewModel中实现的ICommand。

因此,无论是按钮还是F2输入绑定都将执行相同的命令。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接