OK, I implement my closed/closing behaviour
Implementation of the closing event
public partial class Commands
{
#region Closing (Window event)
private static void Window_Closing(object sender, CancelEventArgs e)
{
FrameworkElement element = sender as FrameworkElement;
if (element == null) return;
ICommand command = GetClosingCommand(element);
if(command != null && command.CanExecute(e))
command.Execute(e);
}
public static readonly DependencyProperty ClosingCommandProperty =
DependencyProperty.RegisterAttached("ClosingCommand", typeof(ICommand),
typeof(Commands), new PropertyMetadata(default(ICommand), OnClosingCommandChanged));
public static ICommand GetClosingCommand(DependencyObject d) { return (ICommand)d.GetValue(ClosingCommandProperty); }
public static void SetClosingCommand(DependencyObject d, ICommand value) { d.SetValue(ClosingCommandProperty, value); }
private static void OnClosingCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var element = d as Window;
if (element != null)
{
if (e.OldValue == null && e.NewValue != null)
element.Closing += Window_Closing;
else if (e.OldValue != null && e.NewValue == null)
element.Closing -= Window_Closing;
}
}
#endregion
}
Here's we are reating a dependency property and its get and set methods. Then we emplement a ChangeProperty handle where we add or remove our EventHandle to a framework element (in our case it's window class). Event handler just execute a command with CancelEventArgs param.
E.g. of the command
public ICommand ClosingWindowCommand
{
get
{
return new RelayCommand<canceleventargs>((e)=>
{
MessageBoxResult result = MessageBox.Show(
"Are you sure that want to exit from application?",
"Exit from application",
MessageBoxButton.YesNo, MessageBoxImage.Question);
if (result == MessageBoxResult.No) e.Cancel = true;
});
}
}
</canceleventargs>
Just shows message box with two buttons (Yes, No). If user pressed button No then assign to property Cancel of the CancelEventArgs param value true.
XAML (changing our property and binding command)
<window x:class="MyApplication.View.MainWindow" xmlns:x="#unknown">
x:Name="MainWindowInstance"
...
xmlns:cmd="clr-namespace:MyApplication.Command"
DataContext="{Binding CloseTab,ElementName=MainWindowInstance}"
Title="MainWindow" Height="350" Width="525"
cmd:Commands.ClosingCommand="{Binding ClosingWindowCommand}">
</window>