我正在开发多个实例WPF应用程序。应用程序在主屏幕中有一个网格,双击网格行,它打开子窗口。它还具有从主屏幕双击网格行打开多个子窗口的功能。
如果子窗口处于活动状态,是否可以帮助我阻止父窗口关闭?因此,如果子窗口处于活动状态,用户将无法关闭主窗口。
答案 0 :(得分:2)
将这些子项的所有者属性设置为主窗口:
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,上面的内容将帮助您设置所有者属性。
答案 1 :(得分:0)
在窗口关闭命令传递中,如果子窗口打开,则禁用关闭功能。
或强>
当弹出窗口打开并触发关闭命令时,你可以做的是canexecute = false
。
答案 2 :(得分:0)
将功能附加到主窗口'关闭'事件,并检查子窗口是否打开。如果是,请设置
e.cancel = true;
答案 3 :(得分:0)
您有两种选择:
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;
}
}
}