A command for WPF TextBox that fires when we press Enter Key

It is very easy to bind Button in WPF applications to Command in the VIEWMODEL class. I would like to get a similar binding for a TextBox .

I have a TextBox and I need to bind it to a Command that fires when I press Enter while the TextBox focused. I am currently using the following handler for the KeyUp event, but it looks ugly ... and I cannot put it in the VIEWMODEL class.

 private void TextBox_KeyUp(object sender, KeyEventArgs e) { if (e.Key == System.Windows.Input.Key.Enter) { // your event handler here e.Handled = true; MessageBox.Show("Enter Key is pressed!"); } } 

Is there a better way to do this?

+61
c # wpf icommand
Jul 30 '11 at 9:11
source share
4 answers

Aryan, not every WPF object supports a command. Therefore, if you do not, you will need to either call your look model from your code (a bit related) or use some MVVM Messaging implementation to separate it. See the MVVM Light Messaging toolkit for an example. Or just use triggers like this:

 <TextBox> <i:Interaction.Triggers> <i:EventTrigger EventName="KeyUp"> <i:InvokeDataCommand Command="{Binding MyCommand}"/> </i:EventTrigger> </i:Interaction.Triggers> </TextBox> 
+18
Jul 30 '11 at 9:17
source share

I ran into the same problem and found a solution here , here is a sample code:

 <TextBox> <TextBox.InputBindings> <KeyBinding Command="{Binding Path=CmdSomething}" Key="Enter" /> </TextBox.InputBindings> </TextBox> 
+186
May 05 '12 at 21:53
source share

I like Sarh's answer, but it will not work in my program unless I changed Enter to Return :

 <TextBox> <TextBox.InputBindings> <KeyBinding Key="Return" Command="{}" /> </TextBox.InputBindings> </TextBox> 
+5
Aug 29 '14 at 23:16
source share

You can set true for the AcceptReturn property.

  <TextBox AcceptsReturn="True" /> 
-four
Jan 02 '15 at 12:42
source share



All Articles