前端之家收集整理的这篇文章主要介绍了
WPF MVVM取消Window.Closing事件,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在
WPF应用程序和MVVMLight Toolkit中,我想看看你的意见,如果我需要取消Window Close事件,最好的
方法是什么.
在Window.Closing事件中,我可以设置e.Cancel = true,这可以防止
关闭表单.要确定是否允许Close,或者应该阻止Close是否在
viewmodel上下文中.
一个解决方案可能是如果我定义一个Application变量,我可以在后面的视图代码中的普通事件处理程序中查询它?
谢谢
@H_
403_7@
使用MVVM Light,您获得了EventToCommand:
因此,您可以在xaml中将关闭事件连接到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传递给VM:
您可以始终使用类似的方法使用行为,并使用VM中的简单bool(将此bool绑定到行为)以指示应取消关闭事件.
更新:
Download Link for following example
要使用行为执行此操作,您可以使用以下行为:
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切换此bool,以便您测试行为