How to handle keypress in WPF using MVVM?

Did you want to capture the Enter key on a textbox, or the F3 key for find again in your WPF Application when you are using MVVM?

I was using custom behaviors for a while until I realized I was overcomplicating things far too much.

You can wire up commands right to keys very easily.

Here is a sample. Same concept for any framework control.

[sourcecode language=”csharp”]
<Window.InputBindings>
<KeyBinding Command="{Binding FindNextCommand}" Key="F3"/>
</Window.InputBindings>
[/sourcecode]

If you had a textbox, just set the TextBox.InputBindings and the key to Enter. Happy Coding!

Leave a Reply

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