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