wpf刚学2天,就遇到这个问题
WPF弹出框ShowDialog,第二次弹出就报错是什么回事?
已解决该问题:(主窗体:MainWindow,子窗体:ChooseServer)
第一步:主窗体代码
ChooseServer.ShowDialog("带蒙板的消息框", this);
第二部:子窗体代码
public static void ShowDialog(string message, Window owner) { //蒙板 Grid layer = new Grid() { Background = new SolidColorBrush(Color.FromArgb(128, 0, 0, 0)) }; //父级窗体原来的内容 UIElement original = owner.Content as UIElement; owner.Content = null; //容器Grid Grid container = new Grid(); container.Children.Add(original);//放入原来的内容 container.Children.Add(layer);//在上面放一层蒙板 //将装有原来内容和蒙板的容器赋给父级窗体 owner.Content = container; //弹出消息框 ChooseServer box = new ChooseServer() { Owner = owner }; box.ShowDialog(); } private void Window_Closed(object sender, EventArgs e) { //容器Grid Grid grid = this.Owner.Content as Grid; //父级窗体原来的内容 UIElement original = VisualTreeHelper.GetChild(grid, 0) as UIElement; //将父级窗体原来的内容在容器Grid中移除 grid.Children.Remove(original); //赋给父级窗体 this.Owner.Content = original; }
试试这里的方法:
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true;
this.Visibility = Visibility.Hidden;
}
对应的中文错误信息是
关闭 Window 之后,无法设置 Visibility,也无法调用 Show、ShowDialogor 或 WindowInteropHelper.EnsureHandle。
英文错误信息是
Cannot set Visibility or call Show, ShowDialog, or WindowInteropHelper.EnsureHandle after a Window has closed.
关闭了就释放了很多资源,也就无法使用其他函数。比如你关机了,你按键盘就没作用了。
很简单,你再new 一个好了。