如果一个程序的主页面关闭但是子页面还在,后续关闭子页面时可能导致程序一直无法结束,所以我们把主页面关闭时可以让其将所有子页面关闭,从而将程序结束
我们现在后台.cs文件的窗口初始化中加上 this.Closing += Window_Closing; 将右上角关闭按钮的加入监测中
public Window1()
{
InitializeComponent();
this.Closing += Window_Closing; //添加右上角禁用按钮的检测
}
然后在添加同名检测事件就可以了
private void Window_Closing(object sender, CancelEventArgs e)//右上角禁用按钮 退出程序
{
YesNoWindowDld wnd = new YesNoWindowDld()//弹出box提醒是否退出
{
DataContext = new DialogViewModel() { Title = "退出程序", Info = "确定要退出程序吗?" }
};
wnd.Owner = this;
var result = wnd.ShowDialog();//利用返回值判断是否退出(点击按钮)
if (result == false)
{
//点击了取消
e.Cancel = true;
}
else
{
Window[] childArray = Application.Current.Windows.Cast<Window>().ToArray();
for (int i = childArray.Length; i-- > 0;)//关闭所有子窗体
{
Window item = childArray[i];
if (item.Title == "") continue; // 忽略无标题窗口
if (item.Title != this.Title) item.Close();
}
}
}