WPF 的快捷键

RKT*_*RKT 4 c# wpf xaml

我在我的应用程序中使用了 UserControl,我需要为我的应用程序设置快捷键,我放置了此代码,但不起作用。任何人建议请

我的 XAML 代码

<Button  Name="ucBtnUpload" ToolTip="Upload F2" Cursor="Hand" Click="ucBtnUpload_Click" KeyUp="ucBtnUpload_KeyUp_1" >
Run Code Online (Sandbox Code Playgroud)

我的代码背后

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

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

             }
}
Run Code Online (Sandbox Code Playgroud)

Eld*_*dho 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
        }
}
Run Code Online (Sandbox Code Playgroud)

活动

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");
}
Run Code Online (Sandbox Code Playgroud)

如果您正在关注 MVVM,您可以尝试此参考

<UserControl.InputBindings>
<KeyBinding Modifiers="Control" 
            Key="E" 
            Command="{input:CommandBinding EditCommand}"/>
Run Code Online (Sandbox Code Playgroud)

请参阅参考
msdn 添加键绑定