【问题标题】:How do I suppress menu keyboard shortcut KeyDown handling in WPF?如何在 WPF 中抑制菜单键盘快捷键 KeyDown 处理?
【发布时间】:2011-12-01 03:57:19
【问题描述】:

我有一个具有菜单键盘快捷键和文本框的应用程序。我希望在文本框获得焦点时禁用键盘快捷键,但我想不出一个简单的方法来做到这一点。我可以处理文本框的 PreviewKeyDown 事件,但发送 KeyDown 事件不会触发 TextInput 事件,因此我必须自己手动触发 TextInput 事件,并且我必须确保每个文本框都覆盖PreviewKeyDown 事件并创建一个 TextInput 事件。

这是在文本框有焦点时抑制菜单键盘快捷键的唯一方法,还是有其他不易出错的方法?

编辑:

这是我添加键盘快捷键的方法:

var kgc = new NuiWpfCore.Input.UnrestrictedKeyGestureConverter();  // allows gestures without modifier keys
var result = kgc.ConvertFromString(s) as NuiWpfCore.Input.UnrestrictedKeyGesture;
m_KeyBinding = new KeyBinding();
m_KeyBinding.Command = KeyBindingCommand;
m_KeyBinding.Modifiers = result.Modifiers;
m_KeyBinding.Key = result.Key;
m_Parent.InputBindings.Add(m_KeyBinding); // m_Parent is of type UIElement

【问题讨论】:

    标签: wpf textbox keyboard-shortcuts


    【解决方案1】:

    您能否提供更多输入,如您如何注册键盘快捷键?使用KeyBinding?如果是这样,它已经需要指定Command。因此,如果文本框处于焦点状态,则在命令的 Canexecute 中返回 false。

    这将禁用键盘快捷键。您身边的一些源代码可能会有用。

    编辑

    所以现在你有KeyBinding 使用KeyBindingCommand,在我看来就像RoutedCommand。如果是这样,那么具有CanExecute 功能的命令绑定也是如此。

        m_Parent.CommandBindings.Add(new CommandBinding(KeyBindingCommand, OnExecuted, CanExcute));
    

    CanExecute 处理程序中......CanExecutedRoutedArgs 可能/可能不是正确的......

        private void CanExecute(object sender, CanExecutedRoutedArgs args)
        {
              e.CanExecute = !textBox.IsFocused;
        } 
    

    以上代码仅作说明。

    【讨论】:

    • 我的命令最初不是 RoutedCommand,但将其更改为 RoutedCommand 并按照您的建议解决了我的问题!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    • 1970-01-01
    • 2010-11-24
    • 2013-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多