防止在子窗口处于活动状态时关闭父窗口
本文关键字:窗口 活动状态 | 更新日期: 2023-09-27 18:06:01
我正在开发多实例WPF应用程序。应用程序在主屏幕上有一个网格,双击网格行,它打开子窗口。它还具有在主屏幕上双击网格行打开多个子窗口的功能。
如果子窗口处于活动状态,谁能帮助我防止父窗口关闭?如果子窗口处于活动状态,则用户无法关闭主窗口。
设置这些子节点的Owner属性为Main Windows:
private void Button_Click(object sender, RoutedEventArgs e)
{
var wnd = new Window();
wnd.Owner = this;
wnd.Show();
}
然后在主窗口关闭事件处理程序:
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (this.OwnedWindows.Count > 0)
{
MessageBox.Show("Child windows exists, you have to close'em first");
e.Cancel = true;
}
}
作为最后一点,它可以帮助你知道,你可以从任何地方在你的代码应用程序的主窗口:
System.Windows.Application.Current.MainWindow
如果你使用的是MVVM,上面的内容可以帮助你设置Owner属性
您有两个选择:
1-你可以使用ShowDialog()打开子窗口,但是用户不能与父窗口交互,直到子窗口被关闭。
2-您可以通过检查
来检查当前打开的所有窗口Application.Current.Windows
,然后你可以决定是否要关闭你的窗口
编辑:将以下事件处理程序添加到您的Parent.Closing
事件
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
foreach (var item in Application.Current.Windows)
{
Window window = item as Window;
if (window.Title == "YourChildWindowTitle")
{
// show some message for user to close childWindows
e.Cancel = true;
break;
}
}
}
在窗口关闭命令传递中,如果子窗口打开则禁用关闭功能。
或
你可以做的是让canexecute = false
在弹出窗口打开和关闭命令被触发
给主窗口的'Closing'事件附加一个函数,并检查子窗口是否打开。如果是,则设置
e.cancel = true;