Wpf – How does the WPF Button.IsCancel property work

buttonwpf

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?

Best Answer

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:

public MainWindow()
{
    InitializeComponent();

    this.PreviewKeyDown += new KeyEventHandler(CloseOnEscape);
}

private void CloseOnEscape(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Escape)
        Close();
}
Related Topic