Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing the Enter key in a TextBox

Tags:

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?

like image 763
Hosea146 Avatar asked Apr 05 '11 18:04

Hosea146


People also ask

How do you check if the enter key is pressed?

Check the event. And the following JavaScript code to detect whether the Enter key is pressed: const input = document. querySelector("input"); input. addEventListener("keyup", (event) => { if (event.


2 Answers

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

like image 180
micahtan Avatar answered Sep 28 '22 15:09

micahtan


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> 
like image 24
O.Man Avatar answered Sep 28 '22 13:09

O.Man