WPF MVVM取消Window.Closing事件

pil*_*oft 7 wpf mvvm-light

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

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

谢谢

Viv*_*Viv 15

使用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>
Run Code Online (Sandbox Code Playgroud)

在VM中:

public RelayCommand<CancelEventArgs> ClosingCommand { get; private set; }

ctor() {
  ClosingCommand = new RelayCommand<CancelEventArgs>(args => args.Cancel = true);
}
Run Code Online (Sandbox Code Playgroud)

如果您不想传递CancelEventArgs给VM:

你可以总是采用类似的方法,Behavior只需使用boolVM中的一个简单(将此bool绑定到行为)来指示应该取消关闭事件.

更新:

下载以下示例的链接

要做到这一点Behavior你可以有一个Behavior如下:

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

现在在xaml:

<i:Interaction.Behaviors>
  <local:CancelCloseWindowBehavior CancelClose="{Binding CancelClose}" />
</i:Interaction.Behaviors>
Run Code Online (Sandbox Code Playgroud)

CancelClose来自VM的bool属性在哪里指示是否Closing应该取消该事件.在附带的示例中,我有一个Button从VM切换这个bool应该让你测试Behavior