【问题标题】:WPF Commands. Textbox does not handle char mapped as a hotkeyWPF 命令。文本框不处理映射为热键的字符
【发布时间】:2014-10-19 15:28:38
【问题描述】:

我被 wpf 命令和“非平凡的”热键困住了。我想将“+”键映射到某个命令。在我希望它继续与任何文本框一起工作。下面是示例

Commands.cs

    public static class Commands
    {
        private static readonly ICommand _someCommand;

        static Commands()
        {
            _someCommand = new RoutedCommand("cmd", typeof(Commands), new InputGestureCollection { new KeyGesture(Key.OemPlus), new KeyGesture(Key.Add) });
        }

        public static ICommand SomeCommand
        {
            get { return _someCommand; }
        }
    }

MainWindow.xaml

<Window x:Class="WpfHotkeysTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:wpfHotkeysTest="clr-namespace:WpfHotkeysTest"
        Title="MainWindow" Height="350" Width="525">
    <Window.CommandBindings>
        <CommandBinding Command="wpfHotkeysTest:Commands.SomeCommand" Executed="CommandBinding_OnExecuted"></CommandBinding>
    </Window.CommandBindings>
    <TextBox></TextBox>
</Window>

MainWindow.xaml.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void CommandBinding_OnExecuted(object sender, ExecutedRoutedEventArgs e)
    {
        Debug.WriteLine("COMMAND! " + e.Source);
    }
}

问题是当我专注于文本框时,它在执行命令之前无法处理按下的“+”键。 我希望显示我的密钥,但如何以最好的方式实现呢?

UPD 如果密钥由文本框处理,我不想执行命令。

我知道有属性 CanExecuteRoutingEventArgs.ContinueRouting。但它同时执行命令和文本框处理

【问题讨论】:

  • 您可以为该命令实现CanExecuteRoutingEventHandler,或者在执行命令之前手动检查是否有任何TextBox 被聚焦。如果有任何TextBox 被关注,请不要执行该命令。
  • 是的,到目前为止,我最终得到了这个解决方案。谢谢!
  • 您应该重新考虑您的用例。你真的想要只有“+”作为命令触发器,而不是与例如组合“控制”?少按一个按钮有什么好处?真的值得吗?
  • 我同意 ctrl++ 会更好,但这个问题是关于可用性的,客户希望它是那样的。

标签: wpf command hotkeys


【解决方案1】:

到目前为止我发现的解决方法

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void CommandBinding_OnExecuted(object sender, ExecutedRoutedEventArgs e)
    {
        Debug.WriteLine("COMMAND! " + e.Source);
    }

    private void CommandBinding_OnCanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        if (IsEditableControlSelected())
        {
            e.ContinueRouting = true;
            return;
        }

        e.CanExecute = true;
    }

    private bool IsEditableControlSelected()
    {
        return Keyboard.FocusedElement is TextBox;
    }
}

这让我热泪盈眶,但至少这总比没有好。等待更多解决方案

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-10
    • 2018-03-04
    • 1970-01-01
    • 2011-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多