使用 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>
在虚拟机中:
public RelayCommand<CancelEventArgs> ClosingCommand { get; private set; }
ctor() {
ClosingCommand = new RelayCommand<CancelEventArgs>(args => args.Cancel = true);
}
如果您不想将CancelEventArgs 传递给虚拟机:
您始终可以对Behavior 采取类似的方法,只需使用来自VM 的简单bool(将此布尔值绑定到行为)来指示应取消关闭事件。
更新:
Download Link for following example
要使用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;
}
}
现在在 xaml 中:
<i:Interaction.Behaviors>
<local:CancelCloseWindowBehavior CancelClose="{Binding CancelClose}" />
</i:Interaction.Behaviors>
其中CancelClose 是来自VM 的布尔属性,它指示是否应该取消Closing 事件。在附加的示例中,我有一个 Button 来从 VM 切换此布尔值,这应该可以让您测试 Behavior