处理与WPF / MVVM光工具包中的窗口关闭事件 [英] Handling the window closing event with WPF / MVVM Light Toolkit
问题描述
我想处理关闭事件(当用户点击右上角的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.
我知道如何在$ C $这样做C-背后:订阅窗口关闭事件再使用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。
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,但它不能正常工作(不执行命令的code)。
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;
}
然后将处理程序添加到视图模型
:
public void OnWindowClosing(object sender, CancelEventArgs e)
{
// Handle closing logic, set e.Cancel as needed
}
在这种情况下,您可以通过使用更精细的图案更间接( XML
加命令模式的5个额外的线路),除了获得准确的复杂性无关。
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).
零code-背后的口号本身不是目的,关键是为从视图分离视图模型。即使在事件查看的code-背后所绑定的视图模型
不依赖于查看和闭幕逻辑的可以是单元测试。
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光工具包中的窗口关闭事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!