如何在 WPF 中使用委托命令继续路由


当我

尝试使用文本框时,应用程序中的键绑定正在窃取键关闭消息。所以例如:

<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 接口的委托命令。

问题是键 P,R,I,你不能传播到任何文本框。

有没有办法继续路由?

只要你使用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);
    }
}

最新更新