WPF MVVM取消Window.Closing事件

WPF应用程序和MVVMLight Toolkit中,我想看看你的意见,如果我需要取消Window Close事件,最好的方法是什么.
在Window.Closing事件中,我可以设置e.Cancel = true,这可以防止关闭表单.要确定是否允许Close,或者应该阻止Close是否在viewmodel上下文中.

一个解决方案可能是如果我定义一个Application变量,我可以在后面的视图代码中的普通事件处理程序中查询它?

谢谢

使用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,以便您测试行为

相关文章

Windows2012R2备用域控搭建 前置操作 域控主域控的主dns:自...
主域控角色迁移和夺取(转载) 转载自:http://yupeizhi.blo...
Windows2012R2 NTP时间同步 Windows2012R2里没有了internet时...
Windows注册表操作基础代码 Windows下对注册表进行操作使用的...
黑客常用WinAPI函数整理之前的博客写了很多关于Windows编程的...
一个简单的Windows Socket可复用框架说起网络编程,无非是建...