Wpf – Capturing the Enter key in a TextBox

wpf

In my WPF view, I am trying to tie an event to the Enter key as follows:

<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>

This code works and my EnterKeyCommand fires when the users presses the Enter key. However, the problem is that when the event fires, WPF hasn't yet bound the text in the textbox to 'SearchCriteria'. So when my event fires, the contents of 'SearchCriteria' is blank. Is there a simple change I can make in this code so that I can get the contents of the textbox when my EnterKey command fires?

Best Answer

You need to change the UpdateSourceTrigger on your TextBox.Text binding to PropertyChanged. See here.