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



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

该命令执行正常,但处理它的代码需要知道按下的实际键(请记住,这可能是一个回车键或任何不仅仅是一个字母的东西,所以我无法从 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>

我认为InvokeCommandAction不可能做到这一点,但您可以快速创建自己的Behavior大致如下所示:

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作为命令的参数接收。

最新更新