我正在使用 MVVM 设计原则构建一个 wpf 应用程序。我的 ViewModel 有一个CloseCommand
触发RequestClose
事件的。如果 ViewModel 设置为窗口的数据上下文,则窗口将订阅此事件并Close()
在事件触发时调用自身。
我的问题是用户可以在不通过我的RequestClose
系统的情况下关闭窗口 - 例如,通过单击窗口右上角的“x”。我想覆盖它,以便单击“x”向我的CloseCommand
.
我尝试将此方法附加到窗口上的“关闭”事件中:
void CloseWindow(object sender, CancelEventArgs e)
{
var chwn = sender as ChildWindow;
var dc = chwn.DataContext as AbstractWorkspaceViewModel;
if (openWindows.Any((wn => dc == wn.DataContext))) {
if (dc.CloseCommand.CanExecute(null)) {
dc.CloseCommand.Execute(null);
e.Cancel = true;
}
}
}
CloseCommand
但是,来自(通过之后)的链RequestClose
最终调用了window.Close()
,这会导致以下错误:
"Cannot set Visibility to Visible or call Show, ShowDialog,
Close, or WindowInteropHelper.EnsureHandle while a Window is closing."
我想这是因为即使我已经写e.Cancel = true
了,窗口仍然认为它会关闭,直到稍后。
我想改变我的方法看起来像这样:
if (dc.CloseCommand.CanExecute(null))
dc.CloseCommand.Execute(null);
else
e.Cancel = true;
然后仅window.close()
在窗口尚未关闭时才调用,但我不知道如何确定窗口是否已经关闭。
我该如何解决这个问题?是否可以将窗口上的“x”绑定到我的CloseCommand
?