Capturing the Enter key in a TextBox

Wpf

Wpf Problem Overview


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?

Wpf Solutions


Solution 1 - Wpf

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

Solution 2 - Wpf

You can do this by passing the TextBox's InputBindings property as a CommandParameter to the Command :

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

Solution 3 - Wpf

I know this is 6 years old but none of the answers produce the correct answer in its entirety using XAML and no code-behind.I still had some work to do. For reference the approach is the following. First the 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>

Basically the approach is that every key is tossed to the bound SearchText on every keystroke. Thus the string will be entirely present within SearchText once the return/enter is pressed. Thus in the SearchEnterHit command the entire string within the TextBox is available via the SearchText property.

As mentioned above the UpdateSourceTrigger=PropertyChanged is what flushes every keystroke to the SearchText property. The KeyBindings capture the enter key.

This is really the simplest means of doing this with no code-behind and all XAML. Sure you are flushing keys to the SearchText property often but that generally is not a problem.

Solution 4 - Wpf

You can also do this in the code behind.

[How to: Detect When the Enter Key Pressed][1]

In the check for enter/return, just invoke your event handler code.

[1]: https://msdn.microsoft.com/en-us/library/ms752054(v=vs.110).aspx "How to: Detect When the Enter Key Pressed"

Solution 5 - Wpf

It is also can be done like async event. Here is the example.

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();
      }
  }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHosea146View Question on Stackoverflow
Solution 1 - WpfmicahtanView Answer on Stackoverflow
Solution 2 - WpfO.ManView Answer on Stackoverflow
Solution 3 - WpfsagnetaView Answer on Stackoverflow
Solution 4 - WpfK0D4View Answer on Stackoverflow
Solution 5 - WpfNoWarView Answer on Stackoverflow