如何在WPF中继续使用DelegateCommand进行路由

问题描述 投票:1回答:1

我尝试使用文本框时,应用程序中的KeyBindings正在窃取按键消息。因此,例如:

<ribbon:RibbonWindow.InputBindings>
    <KeyBinding Command="{Binding Review.ReviewReviewedCommand}" CommandParameter="Key" Key="Space" />
    <KeyBinding Command="{Binding Review.ReviewLabelPrivilegedCommand}" CommandParameter="Key" Key="P" />
    <KeyBinding Command="{Binding Review.ReviewLabelRelevantCommand}" CommandParameter="Key" Key="R" />
    <KeyBinding Command="{Binding Review.ReviewLabelIrrelevantCommand}" CommandParameter="Key" Key="I" />
    <KeyBinding Command="{Binding Review.ReviewUnassignDocTypeCommand}" CommandParameter="Key" Key="U" />
</ribbon:RibbonWindow.InputBindings>

使用的命令是具有ICommand接口的DelegateCommands。

问题是键P,R,I,U无法传播到任何文本框。

是否有继续路由的方法?

wpf command icommand
1个回答
0
投票

[只要您使用KeyBinding,没有大量的技巧就无法使用。我为此实现的解决方案是:

  1. 使用KeyDown事件捕获被按下的键(而不是KeyBindings)。这将在代码的后面,然后从那里打开按下的键以调用所需的DataContext's命令(ReviewReviewedCommandReviewLabelPrivilegedCommand等)。
  2. 现在您有其他问题。 TextBox正在获取输入,但是您的键绑定命令也在触发。在后面的代码上,检查keyEventArgs.InputSource的类型,如果它是TextBox,则忽略按键。

应该看起来像这样:

private void OnKeyDown(object sender, KeyEventArgs e)
{
    ICommand command = null;

    switch (e.Key)
    {
        case Key.Space:
            command = ((YourDataContextType)DataContext).ReviewReviewedCommand;
            break;
        case Key.P:
            command = ((YourDataContextType)DataContext).ReviewLabelPrivilegedCommand;
            break;
    }

    bool isSourceATextBox = e.InputSource.GetType() == typeof(TextBox);
    if (command != null && !isSourceATextBox)
    {
        command.Execute(parameter:null);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.