#315 – Setting IsDefault and IsCancel to the Same Button

You normally set either the IsDefault or IsCancel properties on a button, depending on its purpose.  But you can also set both properties to true for the same button.  You’d typically do this on a dialog that only has one button for closing the dialog.  In this case, you’d want the button to activate when the user pressed either ENTER or ESC (Escape).

	            <Button Content="OK" Width="100" Margin="15"
	                    IsDefault="True" IsCancel="True"
	                    Click="OK_Click"/>

Advertisement

#314 – Typical Usage for Default and Cancel Buttons

You’ll typically see Default and Cancel buttons used together in a window or dialog, to provide OK / Cancel functionality.

The idea is that if the user presses the ENTER key, the button marked with the IsDefault property receives a Click event, as if the user had clicked on the OK button.  The data that the user entered in the dialog is accepted and the window disappears.

If the user presses the ESC (Escape) button, the button marked with the IsCancel property receives a Click event, as if the user had clicked on the Cancel button.  The data that the user entered in the dialog is abandoned (not saved) and the window disappears.

#313 – Specify a Cancel Button in a Window

You can use the IsCancel property to specify that a particular button in a window is the cancel button.  You can still click on the button like you would any other button in the window, but if you press the ESC (Escape) key, the cancel button will respond as if it was clicked.  The button responds to the ESC key, no matter which control currently has keyboard focus.

		        <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
		            <Button Content="Save" Width="100" Margin="10,20,10,20"
		                    IsDefault="True"
		                    Click="Save_Click"/>
		            <Button Content="Cancel" Width="100" Margin="10,20,10,20"
                            IsCancel="True"
		                    Click="Cancel_Click"/>
		        </StackPanel>

.