将命令绑定到窗口标题栏的X按钮

时间:2010-05-24 07:28:06

标签: wpf window command binding exit

我的WPF维护窗口有一个带有“退出”按钮的工具栏; CommandExit与此按钮绑定。 CommandExit在退出之前执行一些检查。

现在,如果我点击关闭窗口按钮(标题栏的x按钮),将忽略此检查。

如何将CommandExit绑定到窗口x按钮?

2 个答案:

答案 0 :(得分:6)

我假设您可能希望根据这些条件取消关闭?您需要使用Closing event,它会通过System.ComponentModel.CancelEventArgs取消关闭。

您可以在代码隐藏中挂钩此事件并手动执行命令,或者,这将是首选方法,您可以使用附加行为挂钩事件并触发命令。

有些事情(我还没有测试过):

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

    }
}

答案 1 :(得分:0)

您必须实现主窗口事件“Closing”的事件处理程序,您可以在其中执行检查并取消关闭操作。这是最简单的方法,但是你必须重新设计整个窗口及其主题。

相关问题