捕获TextBox中的Enter键

Hos*_*146 73 wpf

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

此代码有效,当用户按下Enter键时,我的EnterKeyCommand将触发.但问题是,当事件触发时,WPF尚未将文本框中的文本绑定到"SearchCriteria".因此,当我的事件触发时,"SearchCriteria"的内容为空.我可以在此代码中进行简单的更改,以便在我的EnterKey命令触发时可以获取文本框的内容吗?

mic*_*tan 72

你需要改变UpdateSourceTrigger你的TextBox.Text结合PropertyChanged.看到这里.

  • 因此,基本上,他应该将`Text ="{Binding SearchCriteria,Mode = OneWayToSource}"更改为`Text ="{Binding SearchCriteria,Mode = OneWayToSource,UpdateSourceTrigger = PropertyChanged}"`并且它将正常工作. (6认同)

小智 13

您可以通过将TextBox的InputBindings属性作为a CommandParameter传递给Command:

<TextBox x:Name="MyTextBox">
    <TextBox.InputBindings>
        <KeyBinding Key="Return" 
                    Command="{Binding MyCommand}"
                    CommandParameter="{Binding ElementName=MyTextBox, Path=Text}"/>
    </TextBox.InputBindings>
</TextBox>
Run Code Online (Sandbox Code Playgroud)


K0D*_*0D4 8

您也可以在后面的代码中执行此操作.

如何:按下Enter键时检测

在检查输入/返回时,只需调用您的事件处理程序代码.

  • 除非绝对必要,否则通常应避免使用代码隐藏.输入绑定更合适且更具说明性. (5认同)

sag*_*eta 5

我知道这已经有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>
Run Code Online (Sandbox Code Playgroud)

基本上,方法是将每个键都在每次击键时都扔到绑定的SearchText上。因此,一旦按下回车键,该字符串将完全出现在SearchText中。因此,在SearchEnterHit命令中,可通过SearchText属性使用TextBox中的整个字符串。

如上所述,UpdateSourceTrigger = PropertyChanged是将每次击键刷新到SearchText属性的方法。KeyBindings捕获Enter键。

这实际上是最简单的方法,不需要任何代码,也不需要所有XAML。确保您经常刷新SearchText属性的键,但这通常不是问题。