Mark Gilbert's Blog

Science and technology, served light and fluffy.

Dude, where’s my .CancelButton?

One of the minor road bumps I encountered was trying to build the WPF Media Player, and especially the Songs popup list, was how to denote the Close button’s Click event handler to fire when the user hit the Escape key.


In Winforms, the CancelButton property of the form did this trick nicely.  There was also an AcceptButton property that determined which button would be “clicked” when the user hit the Enter key.  These two properties were invaluable when creating Winforms utilities.  When you’re opening and closing the applications over and over (you know, like when you’re debugging the utility initially), being able to slap the Esc or Enter buttons to test something saves a lot of time.

In WPF, however, things have changed.

These two properties have moved from the form to the buttons themselves.  There are now button properties for IsCancel and IsAccept.  As the names suggest, these take Boolean values and define which button will be “clicked” when the user hits Esc or Enter, respectively.

I can’t say that I’m entirely pleased with this move.  With a Winforms form, you could only have at most one button defined as the Cancel button, and at most one as the Accept button (these two could theoretically map to the same button, but doing that would confuse the user, to whom “Enter” means “come on, do something, I don’t have all day!” and “Esc” means “no, wait, stop, I didn’t want that!”).

But with the WPF forms, and the IsCancel property (for example) attached to the buttons, what would happen if I had more than one button defined with “IsCancel=True”?

Would they both fire when the user hit “Esc”?  That could get a little messy, not to mention confusing for the user.

Would the first button in the tab order fire, and the others be ignored?  That could be confusing for the maintenance programmer.

As it turns out, having multiple buttons defined with “IsCancel=True” does neither of these things.  In fact, hitting Esc repeatedly simply tabs between the two (or more) buttons defined in this way.  The Click events never fire; the focus merely jumps around the screen.

The lesson here is that WPF makes it easier to shoot (or is that click?) yourself in the foot.  Take care that when you define a Cancel or Accept button for your form you only define at most one of each.

Ultimately I decided not to use the IsCancel property in the 0.1 release to implement the Esc-key functionality.  However, I’m glad I know where it’s moved to, even if it is a little more quirky than before.


March 29, 2008 - Posted by | WPF/Silverlight

Sorry, the comment form is closed at this time.

%d bloggers like this: