WPF MVVM取消Window.Closing事件 [英] WPF MVVM cancel Window.Closing event
问题描述
在WPF应用程序和MVVMLight Toolkit中,我想听听您的意见,如果需要取消Window Close事件,什么是实现的最佳方法? 在Window.Closing事件中,我可以设置e.Cancel = true,以防止关闭窗体.在ViewModel上下文中确定是否允许关闭或应该禁止关闭.
In WPF application together with MVVMLight Toolkit, I would like to see your opinion, what is the best way to implement if I need to Cancel the Window Close event. In Window.Closing event I can set the e.Cancel = true, which prevents closing the form. To identify if the Close is allowed, or should be prevented is in the ViewModel context.
一种解决方案是,如果我定义一个Application变量,并且可以在后面的视图代码中的常规事件处理程序中查询此变量?
One solution could be if I define an Application variable, and I can query this in the normal event handler in view code behind?
谢谢
推荐答案
使用MVVM Light,您可以获得EventToCommand
:
With MVVM Light you got EventToCommand
:
因此您可以在xaml中将关闭事件连接到VM.
So you could in xaml wire up the closing event to the VM.
<Window ...
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:command="http://www.galasoft.ch/mvvmlight">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Closing">
<command:EventToCommand Command="{Binding ClosingCommand}"
PassEventArgsToCommand="True" />
</i:EventTrigger>
</i:Interaction.Triggers>
并在VM中:
public RelayCommand<CancelEventArgs> ClosingCommand { get; private set; }
ctor() {
ClosingCommand = new RelayCommand<CancelEventArgs>(args => args.Cancel = true);
}
如果您不想将CancelEventArgs
传递给虚拟机:
If you do not want to pass CancelEventArgs
to the VM:
您总是可以对Behavior
采取类似的方法,并且只需在VM中使用简单的bool
(将此布尔值绑定到行为")来指示应该取消关闭事件.
You could always take the similar approach with a Behavior
and just use a simple bool
from the VM(bind this bool to the Behavior) to indicate the closing event should be cancelled.
更新:
要使用Behavior
进行此操作,您可以使用Behavior
,例如:
To do this with a Behavior
you could just have a Behavior
such as:
internal class CancelCloseWindowBehavior : Behavior<Window> {
public static readonly DependencyProperty CancelCloseProperty =
DependencyProperty.Register("CancelClose", typeof(bool),
typeof(CancelCloseWindowBehavior), new FrameworkPropertyMetadata(false));
public bool CancelClose {
get { return (bool) GetValue(CancelCloseProperty); }
set { SetValue(CancelCloseProperty, value); }
}
protected override void OnAttached() {
AssociatedObject.Closing += (sender, args) => args.Cancel = CancelClose;
}
}
现在是xaml:
<i:Interaction.Behaviors>
<local:CancelCloseWindowBehavior CancelClose="{Binding CancelClose}" />
</i:Interaction.Behaviors>
CancelClose
是VM的bool属性,指示是否应取消Closing
事件.在随附的示例中,我有一个Button
可以从VM切换此布尔值,这应该可以让您测试Behavior
Where CancelClose
is a bool property from the VM which indicates if the Closing
event should be cancelled or not. In the attached example I have a Button
to toggle this bool from the VM that should let you test the Behavior
这篇关于WPF MVVM取消Window.Closing事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!