【问题标题】:WPF shortcut key bindingWPF快捷键绑定
【发布时间】:2015-11-03 22:03:26
【问题描述】:

我想将快捷键绑定到我的用户控件 UserControl.InputBindings。

我没有使用 MVVM 或任何其他模式。我只想使用 XAML 文件的代码隐藏文件绑定此密钥。

【问题讨论】:

    标签: c# .net wpf keyboard-shortcuts


    【解决方案1】:

    您可以在 XAML 中进行这样的键绑定:

    <UserControl.InputBindings>
        <KeyBinding Command="{Binding SomeCommand}" Key="F5"/>
    </UserControl.InputBindings>
    

    【讨论】:

    • 这就是我要找的。这将根据 DataContext 绑定命令并解决我的问题。非常感谢。
    【解决方案2】:

    如果你想分配一个键绑定,并且你想从代码隐藏中做到这一点,这将是最简单的方法:

    using System.Windows.Input;
    
    var cmd = new RoutedCommand();
    userControl.InputBindings.Add(new KeyBinding(cmd, your_key_gesture_here));
    userControl.CommandBindings.Add(new CommandBinding(cmd, your_event_handler_here));
    

    your_key_gesture_here替换为你想要触发的快捷键,your_event_handler_here替换为你想要按键按下时触发的方法。

    【讨论】:

    • 感谢您的大力帮助。它使用文件隐藏代码解决了这个问题。
    猜你喜欢
    • 2011-01-23
    • 2016-10-22
    • 2010-11-24
    • 1970-01-01
    • 1970-01-01
    • 2012-04-29
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多