使用 WPF/MVVM Light Toolkit 处理窗口关闭事件 [英] Handling the window closing event with WPF / MVVM Light Toolkit
问题描述
我想处理我的窗口的 Closing
事件(当用户单击右上角的X"按钮时),以便最终显示确认消息或/和取消关闭.
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.
我知道如何在代码隐藏中执行此操作:订阅窗口的 Closing
事件,然后使用 CancelEventArgs.Cancel
属性.
I know how to do this in the code-behind: subscribe to the Closing
event of the window then use the CancelEventArgs.Cancel
property.
但我使用的是 MVVM,所以我不确定这是不是好方法.
But I'm using MVVM so I'm not sure it's the good approach.
我认为最好的方法是将 Closing
事件绑定到我的 ViewModel 中的 Command
.
I think the good approach would be to bind the Closing
event to a Command
in my ViewModel.
我试过了:
<i:Interaction.Triggers>
<i:EventTrigger EventName="Closing">
<cmd:EventToCommand Command="{Binding CloseCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
在我的 ViewModel 中有关联的 RelayCommand
但它不起作用(不执行命令的代码).
With an associated RelayCommand
in my ViewModel but it doesn't work (the command's code is not executed).
推荐答案
我会简单地关联 View 构造函数中的处理程序:
I would simply associate the handler in the View constructor:
MyWindow()
{
// Set up ViewModel, assign to DataContext etc.
Closing += viewModel.OnWindowClosing;
}
然后将处理程序添加到ViewModel
:
Then add the handler to the ViewModel
:
using System.ComponentModel;
public void OnWindowClosing(object sender, CancelEventArgs e)
{
// Handle closing logic, set e.Cancel as needed
}
在这种情况下,通过使用更复杂的模式和更多的间接性(额外的 5 行 XAML 加上 Command
模式),除了复杂性之外,你一无所获.
In this case, you gain exactly nothing except complexity by using a more elaborate pattern with more indirection (5 extra lines of XAML plus Command
pattern).
零代码隐藏"mantra 本身并不是目标,重点是将 ViewModel 与 View 分离.即使事件绑定在视图的代码隐藏中,ViewModel
也不依赖于视图,并且关闭逻辑可以进行单元测试.
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.
这篇关于使用 WPF/MVVM Light Toolkit 处理窗口关闭事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!