How does the WPF Button.IsCancel property work?

后端 未结 4 824
刺人心
刺人心 2020-12-02 20:43

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 butt

4条回答
  •  温柔的废话
    2020-12-02 20:56

    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;
    
    /// 
    /// Attached behavior that keeps the window on the screen
    /// 
    public static class WindowService
    {
       /// 
       /// KeepOnScreen Attached Dependency Property
       /// 
       public static readonly DependencyProperty EscapeClosesWindowProperty = DependencyProperty.RegisterAttached(
          "EscapeClosesWindow",
          typeof(bool),
          typeof(WindowService),
          new FrameworkPropertyMetadata(false, new PropertyChangedCallback(OnEscapeClosesWindowChanged)));
    
       /// 
       /// Gets the EscapeClosesWindow property.  This dependency property 
       /// indicates whether or not the escape key closes the window.
       /// 
       ///  to get the property from
       /// The value of the EscapeClosesWindow property
       public static bool GetEscapeClosesWindow(DependencyObject d)
       {
          return (bool)d.GetValue(EscapeClosesWindowProperty);
       }
    
       /// 
       /// Sets the EscapeClosesWindow property.  This dependency property 
       /// indicates whether or not the escape key closes the window.
       /// 
       ///  to set the property on
       /// value of the property
       public static void SetEscapeClosesWindow(DependencyObject d, bool value)
       {
          d.SetValue(EscapeClosesWindowProperty, value);
       }
    
       /// 
       /// Handles changes to the EscapeClosesWindow property.
       /// 
       ///  that fired the event
       /// A  that contains the event data.
       private static void OnEscapeClosesWindowChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
       {
          Window target = (Window)d;
          if (target != null)
          {
             target.PreviewKeyDown += new System.Windows.Input.KeyEventHandler(Window_PreviewKeyDown);
          }
       }
    
       /// 
       /// Handle the PreviewKeyDown event on the window
       /// 
       /// The source of the event.
       /// A  that contains the event data.
       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();
       }
    }
    

提交回复
热议问题