I am new to WPF and I see the best pattern call MVVM. I have try to deep in it and I see that the command can only execute on a button or menuitem, etc. But I have a doubt how to execute the ViewModel command when I'm focusing on a textbox and hit the enter key when I finish my editing. I have google this but I got nothing from all that answer. So hope all of you help me. How to execute command when hit the enter key in textbox?
Asked
Active
Viewed 3,430 times
2
-
Have a look here http://stackoverflow.com/questions/3413927/executing-viewmodels-command-on-enter-in-textbox – Handsome Greg May 21 '17 at 08:06
-
I guess what you look for is an attached behavior that makes the `Text` property of the textbox update when you hit Enter: http://stackoverflow.com/a/564659/2819245 (also read the comments to this answer). No need for a command, i guess... – May 21 '17 at 08:07
2 Answers
8
In my opinion the easiest way is to use a KeyBinding, which allows you to bind a KeyGesture to an ICommand implementation.
In your case, you can write in your XAML something like this:
<TextBox AcceptsReturn="False">
<TextBox.InputBindings>
<KeyBinding Key="Enter" Command="{Binding YourCommand}" />
</TextBox.InputBindings>
</TextBox>
So when your TextBox
is focused and you press Enter, YourCommand
will be executed.
I hope it can help you.

Il Vic
- 5,576
- 4
- 26
- 37
1
You can achieve your requirement using behaviors in WPF.
In XAML,
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
<TextBox Text="MyText">
<i:Interaction.Behaviors>
<i:BehaviorCollection>
<EventToCommand EventName="TextChanged" Command="{Binding ViewModelCommand}">
**// You can provide other events to be triggered in the EventName property based on your requirement like "Focused" or "UnFocused".Focused event will be fired if you enter into edit mode and UnFocused event will be triggered if you press enter key.**
<i:BehaviorCollection>
</i:Interaction.Behaviors>
</TextBox>
In ViewModel.cs,
Public class ViewModel
{
private Command viewCommand;
public ViewModel()
{
viewCommand = new Command(CommandMethod);
}
public Command ViewModelCommand
{
get { return viewCommand }
set { viewCommand = value}
}
private void CommandMethod()
{
//This method will hit if you modify enter/delete text in the TextBox
}
}

Divakar
- 514
- 1
- 9
- 25
-
This will execute command on every character you typed in textbox, while OP need only on enter – Fabio May 21 '17 at 16:00
-
He can achieve his requirement using Focused and UnFocused events in TextBox rather than TextChanged event – Divakar May 21 '17 at 16:19