Handling the window closing event with WPF / MVVM Light Toolkit

I'd like to handle the "Closing" event (when a user clicks the upper right 'X' button) of my window in order to eventually display a confirm message or/and cancel the closing.

I know how to do this in the code-behind : subscribe to the "Closing" event of the window then use the "CancelEventArgs.Cancel" property.

But I'm using MVVM so I'm not sure it's the good approach.

I think the good approach would be to bind the Closing event to a Command in my ViewModel.

I tried that :

    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Closing">
            <cmd:EventToCommand Command="{Binding CloseCommand}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>

With an associated RelayCommand in my ViewModel but it doesn't work (the command's code is not executed).


I would simply associate the handler in the View constructor:

MyWindow() 
{
    // Set up ViewModel, assign to DataContext etc.
    Closing += viewModel.OnWindowClosing;
}

Then add the handler to the ViewModel :

public void OnWindowClosing(object sender, CancelEventArgs e) 
{
   // Handle closing logic, set e.Cancel as needed
}

In this case, you gain exactly nothing except complexity by using a more elaborate pattern with more indirection (5 extra lines of XML plus command pattern).

The "zero code-behind" mantra is not the goal in itself, the point is to decouple ViewModel from the View . Even when the event is bound in code-behind of the View, the ViewModel does not depend on the View and the closing logic can be unit-tested .


This code works just fine:

ViewModel.cs:

public ICommand WindowClosing
{
    get
    {
        return new RelayCommand<CancelEventArgs>(
            (args) =>{
                     });
    }
}

and in XAML:

<i:Interaction.Triggers>
    <i:EventTrigger EventName="Closing">
        <command:EventToCommand Command="{Binding WindowClosing}" PassEventArgsToCommand="True" />
    </i:EventTrigger>
</i:Interaction.Triggers>

and, of course, the ViewModel is assigned to a DataContext of main container.


This option is even easier, and maybe is suitable for you. In your View Model constructor, you can subscribe the Main Window closing event like this:

Application.Current.MainWindow.Closing += new CancelEventHandler(MainWindow_Closing);

void MainWindow_Closing(object sender, CancelEventArgs e)
{
            //Your code to handle the event
}

All the best.

链接地址: http://www.djcxy.com/p/56124.html

上一篇: WPF MVVM模态叠加对话框仅在视图(而非窗口)

下一篇: 使用WPF / MVVM Light Toolkit处理窗口关闭事件