gpt4 book ai didi

c# - 将 KeyUp 作为参数传递 WPF 命令绑定(bind)文本框

转载 作者:太空狗 更新时间:2023-10-29 21:17:49 27 4
gpt4 key购买 nike

我有一个文本框 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 作为命令的参数。

关于c# - 将 KeyUp 作为参数传递 WPF 命令绑定(bind)文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19008424/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com