tags:

views:

2885

answers:

3

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 it 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?
+7  A: 

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();
}
Steven Robbins
+5  A: 

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:

yournamespace:WindowService.EscapeClosesWindow="True"

Here's the code for the property:

using System.Windows;
using System.Windows.Input;

/// <summary>
/// Attached behavior that keeps the window on the screen
/// </summary>
public static class WindowService
{
   /// <summary>
   /// KeepOnScreen Attached Dependency Property
   /// </summary>
   public static readonly DependencyProperty EscapeClosesWindowProperty = DependencyProperty.RegisterAttached(
      "EscapeClosesWindow",
      typeof(bool),
      typeof(WindowService),
      new FrameworkPropertyMetadata(false, new PropertyChangedCallback(OnEscapeClosesWindowChanged)));

   /// <summary>
   /// Gets the EscapeClosesWindow property.  This dependency property 
   /// indicates whether or not the escape key closes the window.
   /// </summary>
   /// <param name="d"><see cref="DependencyObject"/> to get the property from</param>
   /// <returns>The value of the EscapeClosesWindow property</returns>
   public static bool GetEscapeClosesWindow(DependencyObject d)
   {
      return (bool)d.GetValue(EscapeClosesWindowProperty);
   }

   /// <summary>
   /// Sets the EscapeClosesWindow property.  This dependency property 
   /// indicates whether or not the escape key closes the window.
   /// </summary>
   /// <param name="d"><see cref="DependencyObject"/> to set the property on</param>
   /// <param name="value">value of the property</param>
   public static void SetEscapeClosesWindow(DependencyObject d, bool value)
   {
      d.SetValue(EscapeClosesWindowProperty, value);
   }

   /// <summary>
   /// Handles changes to the EscapeClosesWindow property.
   /// </summary>
   /// <param name="d"><see cref="DependencyObject"/> that fired the event</param>
   /// <param name="e">A <see cref="DependencyPropertyChangedEventArgs"/> that contains the event data.</param>
   private static void OnEscapeClosesWindowChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
   {
      Window target = (Window)d;
      if (target != null)
      {
         target.PreviewKeyDown += new System.Windows.Input.KeyEventHandler(Window_PreviewKeyDown);
      }
   }

   /// <summary>
   /// Handle the PreviewKeyDown event on the window
   /// </summary>
   /// <param name="sender">The source of the event.</param>
   /// <param name="e">A <see cref="KeyEventArgs"/> that contains the event data.</param>
   private static void Window_PreviewKeyDown(object sender, KeyEventArgs e)
   {
      Window target = (Window)sender;

      // If this is the escape key, close the window
      if (e.Key == Key.Escape)
         target.Close();
   }
}
John Myczek
Yes. Attached properties still don't 'click' instantly in my head.
Gishu
A: 

Did anyone by any chance figure out the way to Cancel the Cancel event ? With IsCancel=True configuration, it seems Window.Close() will be called by the Framework outside of the Cancel_Click event.

Basically with IsCancel=True, Cancel leads to Closing no questions asked. For situations when one would like to ask user for confirmation IsCancel flag has to be set to false and window closed yourself.

Sergey Malyan
Override Window.OnClosing - you can cancel the Close operation there. That used to work in Winforms - I assume it should work the same for WPF as well
Gishu