Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keyboard events in a WPF MVVM application?

Tags:

mvvm

wpf

How can I handle the Keyboard.KeyDown event without using code-behind? We are trying to use the MVVM pattern and avoid writing an event handler in code-behind file.

like image 618
Carlos Avatar asked Mar 04 '09 23:03

Carlos


People also ask

Which keyboard event is used for script runs when key is pressed?

keypress – fires when you press a character keyboard like a , b , or c , not the left arrow key, home, or end keyboard, … The keypress also fires repeatedly while you hold down the key on the keyboard.

How does WPF MVVM work?

The single most important aspect of WPF that makes MVVM a great pattern to use is the data binding infrastructure. By binding properties of a view to a ViewModel, you get loose coupling between the two and entirely remove the need for writing code in a ViewModel that directly updates a view.

Do you have to use MVVM with WPF?

WPF assumes MVVM for most things. e.g. using a the wpf tree control without MVVM will have you tearing your hair out within a day.. MVVM just makes things simpler and testable. This could answer some of the questions: wintellect.com/CS/blogs/jlikness/archive/2010/04/14/….

What is MVVM command?

Commands are an implementation of the ICommand interface that is part of the . NET Framework. This interface is used a lot in MVVM applications, but it is useful not only in XAML-based apps.


1 Answers

To bring an updated answer, the .net 4.0 framework enables you to do this nicely by letting you bind a KeyBinding Command to a command in a viewmodel.

So... If you wanted to listen for the Enter key, you'd do something like this:

<TextBox AcceptsReturn="False">     <TextBox.InputBindings>         <KeyBinding              Key="Enter"              Command="{Binding SearchCommand}"              CommandParameter="{Binding Path=Text, RelativeSource={RelativeSource AncestorType={x:Type TextBox}}}" />     </TextBox.InputBindings> </TextBox> 
like image 156
koni Avatar answered Sep 21 '22 12:09

koni