How to Close a Window in WPF on a escape key

前端 未结 4 2101
青春惊慌失措
青春惊慌失措 2020-12-24 10:49

Possible Duplicate:
How can I assign the 'Close on Escape-key press' behavior to all WPF windows within a project?

4条回答
  •  长情又很酷
    2020-12-24 11:17

    You can create a custom DependencyProperty:

    using System.Windows;
    using System.Windows.Input;
    
    public static class WindowUtilities
    {
        /// 
        /// Property to allow closing window on Esc key.
        /// 
        public static readonly DependencyProperty CloseOnEscapeProperty = DependencyProperty.RegisterAttached(
           "CloseOnEscape",
           typeof(bool),
           typeof(WindowUtilities),
           new FrameworkPropertyMetadata(false, CloseOnEscapeChanged));
    
        public static bool GetCloseOnEscape(DependencyObject d)
        {
            return (bool)d.GetValue(CloseOnEscapeProperty);
        }
    
        public static void SetCloseOnEscape(DependencyObject d, bool value)
        {
            d.SetValue(CloseOnEscapeProperty, value);
        }
    
        private static void CloseOnEscapeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is Window target)
            {
                if ((bool)e.NewValue)
                {
                    target.PreviewKeyDown += Window_PreviewKeyDown;
                }
                else
                {
                    target.PreviewKeyDown -= Window_PreviewKeyDown;
                }
            }
        }
    
        private static void Window_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (sender is Window target)
            {
                if (e.Key == Key.Escape)
                {
                    target.Close();
                }
            }
        }
    }
    

    And use it your windows' XAML like this:

    
    

    The answer is based on the content of the gist referenced in this answer.

提交回复
热议问题