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

Der*_*nch 6 c# wpf xaml mvvm

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

该命令执行正常,但处理它的代码需要知道按下的实际键(记住这可能是一个输入键或任何不仅仅是一个字母,所以我无法从TextBox.text获取它).

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

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

dmu*_*ial 9

我不认为使用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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后将其附加到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>
Run Code Online (Sandbox Code Playgroud)

只有这样你才能收到Key命令的参数.