【问题标题】:Pass KeyUp as parameter WPF Command Binding Text Box将 KeyUp 作为参数传递 WPF 命令绑定文本框
【发布时间】:2013-10-01 06:02:50
【问题描述】:

我有一个与 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>

【问题讨论】:

标签: c# wpf xaml mvvm


【解决方案1】:

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

【讨论】:

  • 嘿,对不起,我现在意识到我想要完整的事件参数(不仅仅是按下的键),但你的答案适用于按键,关于如何获得完整事件参数的任何提示?
  • 是的,这对我有用 - 非常感谢(只需执行 .Execute(e) 而不是 .Execute(e.key) 即可提供完整的事件参数。太棒了!
  • 对于特殊键(如 enter、tab、up、down 等)没有传递事件。如何也为它们获取 KeyEvent?仅供参考,我使用的是 KeyDown 而不是 KeyUp 并使用自定义文本框。它适用于字母和数字等其他按钮。
猜你喜欢
  • 2018-11-13
  • 1970-01-01
  • 2017-12-17
  • 1970-01-01
  • 2012-03-25
  • 2017-02-27
  • 1970-01-01
  • 1970-01-01
  • 2010-11-04
相关资源
最近更新 更多