The basic idea behind a Cancel button is to enable closing your window with an Escape Keypress.
You can set the IsCancel property on the Cancel button to true, causing the Cancel button to automatically close the dialog without handling the Click event.
Source: Programming WPF (Griffith, Sells)
So this should work
<Window>
<Button Name="btnCancel" IsCancel="True">_Close</Button>
</Window>
However the behavior I expect isn't working out for me. The parent window is the main application window specified by the Application.StartupUri property. What works is
<Button Name="btnCancel" IsCancel=True" Click="CloseWindow">_Close</Button>
private void CloseWindow(object sender, RoutedEventArgs)
{
this.Close();
}
- Is the behavior of IsCancel different based on whether the Window is a normal window or a Dialog? Does IsCancel work as advertised only if ShowDialog has been called?
- Is an explicit Click handler required for the button (with IsCancel set to true) to close a window on an Escape press?
This isn't quite right is it... MSDN says this: When you set the IsCancel property of a button to true, you create a Button that is registered with the AccessKeyManager. The button is then activated when a user presses the ESC key. So you do need a handler in your code behind And you don't need any attached properties or anything like that
We can take Steve's answer one step further and create an attached property that provides the "escape on close" functionality for any window. Write the property once and use it in any window. Just add the following to the window XAML:
Here's the code for the property:
Yes this is right.In windows Application in WPF AcceptButton and Cancel Button is there. But one thing is that if you are setting your control visibility as false, then it won't work as expected.For that you need to make as visibility as true in WPF. For example: (it is not working for Cancel button because here visibility is false)
So, you need make it:
Then you have write
btnClose_Click
in code behind file:Yes, it only works on dialogs as a normal window has no concept of "cancelling", it's the same as DialogResult.Cancel returning from ShowDialog in WinForms.
If you wanted to close a Window with escape you could add a handler to PreviewKeyDown on the window, pickup on whether it is Key.Escape and close the form: