Model-View-ViewModel, Commands and InputBindings

Article updated ! I find out that the Command property of the KeyBinding class is not a DependencyProperty… This prevent using the syntax I wanted (binding to an ICommand exposed in the ViewModel). There are several workarounds you can find across the web (using a MarkupExtension, an attached properies…) but because I didn’t have much time, I finally put some glue in my code-behind ;(

I’m still playing with MVVM those days and today, I needed a simple behavior I didn’t know how to do with MVVM. I finally found a simple solution and as I love them, it’s 100% XAML :p

The problem is simple, I have a ListBox where the user can type date in it.
When the User Validate his input, I need to process the text entered and return another value.
The User can validate the input by pressing the Enter key while the TextBox has the focus.

My first attempt was the subscribe to the KeyUp event, and in the code-behind, delegate the work to the associated ViewModel class. I don’t like that solution a lot (events handler in code-behind are sort of ugly…).

I know I could define an ICommand in my ViewModel and do the work directly there (using the excellent RelayCommand class written by Josh Smith). The problem was how to trigger this command when the Enter key is pressed. well, actually it’s pretty simple:

    
        
            
            
            
                    
    

As I updated the article (because Command is not a DP), I finally did the same thing in C# in the code-behind…

Leave a Reply

Your email address will not be published.