将KeyUp作为参数传递 WPF 命令绑定 文本框

7

我已经在WPF中将文本框的KeyUp事件触发器连接到一个命令中。我需要将实际按下的键作为命令参数传递。

命令可以正常执行,但是处理它的代码需要知道实际按下的键(请记住这可能是回车键或其他任何键,因此无法从TextBox.text中获取)。

无法弄清如何做到这一点。 XAML:

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

XAML:

<TextBox Height="23" Name="TextBoxSelectionSearch" Width="148" Tag="Enter Selection Name" Text="{Binding Path=SelectionEditorFilter.SelectionNameFilter,UpdateSourceTrigger=PropertyChanged}" >
       <i:Interaction.Triggers>
          <i:EventTrigger EventName="KeyUp">
             <i:InvokeCommandAction Command="{Binding SelectionEditorSelectionNameFilterKeyUpCommand}" />
          </i:EventTrigger>
       </i:Interaction.Triggers>
</TextBox>

我使用了MVVMLight,并且可以像这样传递EventArgs:https://dev59.com/CW025IYBdhLWcg3wHSGn#6205643 - Bolu
1个回答

10

我不认为使用InvokeCommandAction实现这个是可能的,但你可以快速创建自己的Behavior,它大致可以看起来像这样:

我认为使用InvokeCommandAction无法实现此功能,但您可以快速创建自己的行为,其大致外观可能如下所示:

public class KeyUpWithArgsBehavior : Behavior<UIElement>
{
    public ICommand KeyUpCommand
    {
        get { return (ICommand)GetValue(KeyUpCommandProperty); }
        set { SetValue(KeyUpCommandProperty, value); }
    }

    public static readonly DependencyProperty KeyUpCommandProperty =
        DependencyProperty.Register("KeyUpCommand", typeof(ICommand), typeof(KeyUpWithArgsBehavior), new UIPropertyMetadata(null));


    protected override void OnAttached()
    {
        AssociatedObject.KeyUp += new KeyEventHandler(AssociatedObjectKeyUp);
        base.OnAttached();
    }

    protected override void OnDetaching()
    {
        AssociatedObject.KeyUp -= new KeyEventHandler(AssociatedObjectKeyUp);
        base.OnDetaching();
    }

    private void AssociatedObjectKeyUp(object sender, KeyEventArgs e)
    {
        if (KeyUpCommand != null)
        {
            KeyUpCommand.Execute(e.Key);
        }
    }
}

然后将其附加到TextBox上:

<TextBox Height="23" Name="TextBoxSelectionSearch" Width="148" Tag="Enter Selection Name" Text="{Binding Path=SelectionEditorFilter.SelectionNameFilter,UpdateSourceTrigger=PropertyChanged}" >
   <i:Interaction.Behaviors>
          <someNamespace:KeyUpWithArgsBehavior
                 KeyUpCommand="{Binding SelectionEditorSelectionNameFilterKeyUpCommand}" />
   </i:Interaction.Behaviors>
</TextBox>

你只需将 Key 作为参数传递给该命令即可。


抱歉,我现在意识到我需要完整的事件参数(不仅仅是按键),但你的答案适用于按键事件,有没有关于如何获取完整事件参数的提示? - DermFrench
没错,这对我有用 - 非常感谢(只需执行.Execute(e)而不是.Execute(e.key),即可获得完整的事件参数。太棒了!) - DermFrench
事件没有传递给特殊键,如回车、制表符、向上、向下等。我怎样才能获取它们的KeyEvent?顺便说一下,我正在使用KeyDown而不是KeyUp,并且使用自定义文本框。对于其他按钮,如字母和数字,它可以正常工作。 - lukai

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接