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?
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.
You need to change the UpdateSourceTrigger
on your TextBox.Text
binding to PropertyChanged
. See here.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With