捕获 TextBox 中的 Enter 键

在我的 WPF 视图中,我试图将一个事件与 Enter 键绑定如下:

<TextBox Width="240" VerticalAlignment="Center" Margin="2" Text="{Binding SearchCriteria, Mode=OneWayToSource}">
<TextBox.InputBindings>
<KeyBinding Key="Enter" Command="{Binding EnterKeyCommand}"/>
<KeyBinding Key="Tab" Command="{Binding TabKeyCommand}"/>
</TextBox.InputBindings>
</TextBox>

这段代码可以工作,当用户按下 Enter 键时,我的 EnterKeyCommand 会触发。但是,问题是当事件触发时,WPF 还没有将文本框中的文本绑定到“ SearchCriteria”。因此,当我的事件触发时,“ SearchCriteria”的内容是空白的。在这段代码中是否可以进行简单的更改,以便在 EnterKey 命令激发时获取文本框的内容?

97168 次浏览

您需要更改 TextBox.Text绑定到 PropertyChangedUpdateSourceTrigger。参见 给你

您还可以在后面的代码中执行此操作。

如何: 检测何时按下回车键

在输入/返回检查中,只需调用事件处理程序代码。

为此,可以将 TextBox 的 InputBindings属性作为 CommandParameter传递给 Command:

<TextBox x:Name="MyTextBox">
<TextBox.InputBindings>
<KeyBinding Key="Return"
Command="{Binding MyCommand}"
CommandParameter="{Binding ElementName=MyTextBox, Path=Text}"/>
</TextBox.InputBindings>
</TextBox>

我知道这是6年前的问题,但是没有一个答案使用 XAML 完整地生成正确的答案,也没有代码隐藏。我还有工作要做。作为参考,方法如下。首先是 XAML

 <TextBox Text="{Binding SearchText, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
<TextBox.InputBindings>
<KeyBinding Key="Enter" Command="{Binding SearchEnterHit}"/>
<KeyBinding Key="Return" Command="{Binding SearchEnterHit}"/>
</TextBox.InputBindings>
</TextBox>

基本上,这种方法是在每次按键时将每个键抛给绑定的 SearchText。因此,一旦按下返回/回车键,字符串将完全出现在 SearchText 中。因此,在 SearchEnterhit命令中,TextBox 中的整个字符串可以通过 SearchText 属性获得。

如上所述,UpdateSourceTrigger = PropertyChanged 是将每次击键刷新到 SearchText属性的工具。

这确实是在没有代码隐藏和全部 XAML 的情况下实现此目的的最简单方法。当然,您经常刷新 SearchText 属性的键,但这通常不是问题。

它也可以像异步事件一样进行。 下面是一个例子。

tbUsername.KeyDown += async (s, e) => await OnKeyDownHandler(s, e);


private async Task OnKeyDownHandler(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
if (!string.IsNullOrEmpty(tbUsername.Text) && !string.IsNullOrEmpty(tbPassword.Password))
{
Overlay.Visibility = Visibility.Visible;
await Login();
}
}
}