WPF命令。 Textbox不处理作为热键映射的char

时间:2014-08-26 10:27:23

标签: wpf command hotkeys

我坚持使用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。但它执行命令和文本框处理

1 个答案:

答案 0 :(得分:0)

到目前为止我找到的解决方法

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;
    }
}

这给我的眼睛带来了泪水,但至少这比没有好。等待更多解决方案