我的WPF维护窗口具有带“退出”按钮的工具栏;一个CommandExit绑定这个按钮。 CommandExit在退出前执行一些检查。将命令绑定到窗口标题栏的X按钮
现在,如果我点击关闭窗口按钮(标题栏的x按钮),这个检查将被忽略。
我怎样才能将CommandExit绑定到窗口x按钮?
我的WPF维护窗口具有带“退出”按钮的工具栏;一个CommandExit绑定这个按钮。 CommandExit在退出前执行一些检查。将命令绑定到窗口标题栏的X按钮
现在,如果我点击关闭窗口按钮(标题栏的x按钮),这个检查将被忽略。
我怎样才能将CommandExit绑定到窗口x按钮?
你要实现你的主窗口的事件“关闭”在这里你可以做检查,并取消关闭动作的事件处理程序。这是最简单的方法,但是否则你必须重新设计整个窗口及其主题。
我想你可能想取消基于这些条件的关闭?你需要使用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;
}
}
}