【问题标题】:Shortcut hotkey for WPFWPF 的快捷键
【发布时间】:2016-10-22 20:19:48
【问题描述】:

我在我的应用程序中使用了 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 中的事件? &lt;ucBtnUpload ... OnClick="ucBtnUpload_KeyUp_1"...&gt;
  • 您确定要在按钮上添加按键事件吗?这要求按钮是 Focused...
  • 通常您通过 WPF 中的 InputBindings 和命令来执行此操作,而不是通过拦截关键事件并处理它们。
  • 是的,当我使用示例应用程序时,我的工作也很好,但我将它用于我的项目,什么都不会发生。这就是为什么我提到我将它用于我的应用程序的用户控制

标签: c# wpf xaml


【解决方案1】:

您需要尝试类似的方法

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

【讨论】:

    【解决方案2】:

    您应该能够在您的 xaml 中执行此操作

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

    MyCommand 是在您的窗口/视图的视图模型中实现的 ICommand。

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

    【讨论】:

      猜你喜欢
      • 2010-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-01
      • 2014-03-30
      • 1970-01-01
      相关资源
      最近更新 更多