您可以编写并Attached behavior
处理Window.Closing()
Window 的事件并执行ClosingCommand
fromViewModel
并返回 true 或 false 作为参数,以便e.Cancel
在 VM 想要停止关闭窗口时取消 () 关闭事件。
下面的代码只是概念,并不完整
XAML
<Window x:Class="..."
...
myBheaviors:WindowBehaviors.ClosingCommand="{Binding MyClosingCommand}">
...
</Window>
视图模型
public class MyWindowViewModel
{
public ICommand MyClosingCommand
{
get
{
if (_myClosingCommand == null)
_myClosingCommand
= new DelegateCommand<CancelEventArgs>(OnClosing);
return _myClosingCommand;
}
}
private void OnClosing(CancelEventArgs e)
{
if (this.Dirty) //Some function that decides if the VM has pending changes.
e.Cancel = true;
}
}
依附行为
public static class WindowBehaviors
{
public static readonly DependencyProperty ClosingCommandProperty
= DependencyProperty.RegistsrrAttached(
"ClosingCommand",
...,
new PropertyMetataData(OnClosingCommandChanged);
public static ICommand GetClosingCommand(...) { .. };
public static void SetClosingCommand(...) { .. };
private static void OnClosingCommandChanged(sender, e)
{
var window = sender as Window;
var command = e.NewValue as ICommand;
if (window != null && command != null)
{
window.Closing
+= (o, args) =>
{
command.Execute(args);
if (args.Cancel)
{
MessageBox.Show(
"Window has pending changes. Cannot close");
// Now window will be stopped from closing.
}
};
}
}
}
编辑:
对于用户控件,而不是Closing
使用Unloaded
事件。
另外尝试建立ViewModel
siee Window的ViewModel之间的层次结构应该包含UserControl的ViewModel。因此,该Closing
事件的 IsDirty() 调用也可以检查 UserControls 的 ViewModel。