通过我自己的命令发送窗口的“关闭”命令

本文关键字:命令 关闭 窗口 我自己 自己的 | 更新日期: 2023-09-27 18:32:07

我正在使用MVVM设计原则构建一个wpf应用程序。我的视图模型有一个触发RequestClose事件的CloseCommand。如果将 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

通过我自己的命令发送窗口的“关闭”命令

如何在

Windows XAML中设置Window.WindowStyle = "None"(隐藏顶部按钮和镶边),然后添加您自己的"假"铬和按钮,您可以根据需要连接