6

I've a Text box KeyUp Event Trigger Wired up to a command in WPF. I need to pass the actual key that was pressed as a command parameter.

The command executes fine, but the code that handles it needs to know the actual key that was pressed (remember this could be an enter key or anything not just a letter, so I can't get it from the TextBox.text).

Can't figure out how to do this. 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>
4

1 回答 1

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);
        }
    }
}

然后将其附加到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作为命令的参数。

于 2013-09-25T16:51:59.053 回答