Bind command to X-button of window title bar

北战南征 提交于 2019-12-04 21:54:25

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.

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;
        }

    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!