How to handle action on enter key press in textbox in WPF

Did you want your OK button or your commit action to take place when you hit enter in a text field in a WPF dialog? You may have implemented a Find dialog, or maybe you have a one field text entry and you want the Enter key to commit the action.

Well, its actually really easy once you learn the simple trick to wiring up the commands.

I have a command called SaveProcessCommand on my viewmodel. I have it wired to my dialogs “OK” button. I also wanted the user to just hit Enter when they were done typing, since that is how my usability study determined users expect.

Enter the simple InputBinding. Pretty cool.

[csharp] <TextBox Margin="10,0,0,0" HorizontalAlignment="Stretch" Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Grid.Column="1">
<KeyBinding Command="{Binding SaveProcessCommand}" Key="Enter"/>

I have the binding to the property update on each keystroke, so it is always up to date. The InputBinding then wires up the Enter key to a command. The command can do whatever you want, you are using MVVM right? Happy Coding!

3 thoughts on “How to handle action on enter key press in textbox in WPF”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.