The source code contains a simple solution with a WPF form that illustrates the use of these properties.
Introduction
How many times did you have to fill a from and had to either use the mouse to click the "save" / "continue" / "insert" / "cancel" button, or click the Tab button until you're on the right button, and then hit Enter?
I've seen commercial applications that suffer from this problem, and it's amusing because it's so easy to solve.
Normal Use Case
You have a form that ends in one of two typical manners:
- The user is happy and hits the "Save" or "Continue" button.
- The user gets annoyed / changes his mind / decides it's all too much for him, and hits the "Cancel" button.
Using good MVVM approach, some developers will be tempted to have command on the TextBox
es or maybe even some code on their code behind that looks for an "Enter" and will then run the "Save" command. Now, it can be done, but it's a waste of time and resources since there's a much simpler solution: the Button
's IsDefault
and IsCancel
properties.
<Button IsDefault="true"
Click= "SaveClicked"
Content="Save" ... />
This bit of magic will cause the "Enter" key to be registered with the AccessKeyManager, so whenever you hit the "Enter" in a TextBox in that form, it will invoke the buttons Click command.
Same goes for the cancel (so whenever you hit the "Esc" key, your cancel button will fire), only you'll use this code:
<Button IsCancel="true"
Click="CancelClicked"
Content="Cancel" ... />
When to Use
I found this useful when editing an object. Double clicking the object will open a new window / view, where I can update the fields and either hit Enter to save or Esc to cancel and go back to the previous page (some magic had to be cast in order to know which was the last view with MVVM, but that's for another post).
Other Things To Do
In a production environment, you'll probably want to set the IsEnabled
to react to some type of data validation on your form/view (for more on Binding.ValidationRules
, look at MSDN). If you do, and you set your IsEnabled
property of the button to False
, then hitting the Enter key will do nothing (since the button is Disabled). Same goes for the Cancel.
(If you're using MVVM-Light or any similar IoC framework, you should have the CanExecute
on the RelayCommand
, which will do this for you).
Other Thoughts
Always keep usability and simplicity in your mind when designing and wiring your forms/windows/views.
If a user finds your application tedious to use, he won't use it (or worse yet, if he has to use it, he'll curse the person who wrote it, which is you).
Little things like this, where things seem to simply work, make the experience much smoother and helps your user get things done instead of wasting time fighting the design.
History
- 10/09/13: Initial release