I am practicing on how to write a WPF application with MVVM pattern. So far I haven't used command in my code. In my Viewmodel I implement INotifyPropertyChanged
and used (event PropertyChangedEventHandler PropertyChanged
) to fire events.
Why do I feel like I still miss some concept of WPF about how to use command?
When is it appropriate to use commands?
The fun thing is that using original Commands concept from WPF is absolutely not required :). You could build large and complex applications with all that beauty of loosely coupled design (xaml) and business logic (c#/vb code) in place with just using MVVM all around and free open source application framework library Caliburn.Micro.
Disclaimer: I'm just a happy user of this library and have nothing to do with its creators, so this is not paid ads or something like that.
Please, just take a look over this very basic sample from official documentation:
--> Basic Configuration, Actions and Conventions <--
and you will fill the power of binding events from you XAML view directly to methods in your C# view-model without mess of proxy code for commands declaration and registration (like this is implemented in other similar application frameworks).
And never mind that this sample is Silverligh app - Caliburn.Micro support all major Xaml platforms almost the same way and the WPF sample will looks pretty like above Silverlight-based.
In addition to the mentioned major capability (buinding to methods) Caliburn.Micro have:
Just give it the chance and you will never need vanilla WPF Commands ;)
Commands in WPF are used to abstract an user-triggered action (such as clicking a
Button
or pressing a key.here's a basic example:
Suppose you want to search for employees in your database when the user clicks the "Search" button, or hits the enter key while focusing the Search Box.
You might define your ViewModel like this:
And your View:
Notice how the
KeyBinding
and the Button'sCommand
property are both bound to the same Command (SearchCommand
) in the ViewModel. This facilitates reutilization, and also helps keep actual logic in the ViewModel, with all its goodness (testability, etc), while keeping the view clean and code-less.