WPF的快捷键热键

时间:2016-06-21 10:22:02

标签: c# wpf xaml

我使用UserControl作为我的应用程序,我需要为我的应用程序添加快捷键我放置此代码但不工作。任何建议PLZ

我的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();

             }
}

2 个答案:

答案 0 :(得分:2)

您需要尝试与此相似的内容

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,可以试试这个reference

<UserControl.InputBindings>
<KeyBinding Modifiers="Control" 
            Key="E" 
            Command="{input:CommandBinding EditCommand}"/>

See the reference
msdn adding key bindings

答案 1 :(得分:0)

您应该可以在xaml中执行此操作

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

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

MyCommand是在您的窗口中实现的ICommand&#39; / view的viewmodel。

因此按钮和F2输入绑定都将执行相同的命令。