Bind command to X-button of window title bar

2019-04-17 18:18发布

问题:

My WPF maintenance window have a toolbar with a button "Exit"; a CommandExit is bind with this button. The CommandExit perform some checks before exit.

Now, if I click to close button of the window (x-button of title bar), this checks are ignored.

How can I do to bind CommandExit to window x-button?

回答1:

You have to implement event handler of your main window's event "Closing" where you can do checks and cancel the closing action. This is easiest way to do it, however otherwise you have to redesign whole window and its theme.



回答2:

I assume you may want to cancel closing based on these conditions? You need to use the Closing event, which passes you a System.ComponentModel.CancelEventArgs to cancel the close.

You can either hook this event in code-behind and execute the command manually, or, and this would be the preferred approach, you could use an attached behavior to hook the event and fire the command.

Something along the lines of (and I haven't tested this) :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Interactivity;
using System.Windows.Input;

namespace Behaviors
{
    public class WindowCloseBehavior : Behavior<Window>
    {
        /// <summary>
        /// Command to be executed
        /// </summary>
        public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(WindowCloseBehavior), new UIPropertyMetadata(null));

        /// <summary>
        /// Gets or sets the command
        /// </summary>
        public ICommand Command
        {
            get
            {
                return (ICommand)this.GetValue(CommandProperty);
            }

            set
            {
                this.SetValue(CommandProperty, value);
            }
        }

        protected override void OnAttached()
        {
            base.OnAttached();

            this.AssociatedObject.Closing += OnWindowClosing;
        }

        void OnWindowClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (this.Command == null)
                return;

            // Depending on how you want to work it (and whether you want to show confirmation dialogs etc) you may want to just do:
            // e.Cancel = !this.Command.CanExecute();
            // This will cancel the window close if the command's CanExecute returns false.
            //
            // Alternatively you can check it can be excuted, and let the command execution itself
            // change e.Cancel

            if (!this.Command.CanExecute(e))
                return;

            this.Command.Execute(e);
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();

            this.AssociatedObject.Closing -= OnWindowClosing;
        }

    }
}