0

I have a MainWindow page and a LoadingWindow. The MainWindow has a button that closes itself and opens LoadingWindow. What I want is when the user closes the Loading window to go back to the MainWindow as a new instance.

MainWindow.xaml.cs

   private void Button_Click(object sender, RoutedEventArgs e)
   {
       LoadingWindow load = new LoadingWindow(calibration , "MainWindow" , this);
       Mouse.OverrideCursor = null;
       Application.Current.MainWindow.Close();
       load.ShowDialog();  //  Exception is here the next time it is called
   }

LoadingWindow.xaml.cs

private void Close_Button(object sender, RoutedEventArgs e)
{
     MainWindow main = new MainWindow();
     this.Close();
     main.ShowDialog();
}

Now when I try to close the Loading window and press the Button_Click, the following error shows up at the load.ShowDialog() although I am declaring a new instance of it.


System.InvalidOperationException: Cannot set Visibility or call Show, ShowDialog, or WindowInteropHelper.EnsureHandle after a Window has closed

I read that you cannot open a window after you closed it, but I am having a new instance which should not make this problem.

Hasan H
  • 142
  • 11
  • WPF has a concept of the main window. Let's alias this as starting window. Often the starting window is an instance of mainwindow. When you close the starting window down then the app closes. Meaning you'll then have another problem when you get this working. You can set what the main window is and you can change the behaviour but maybe your design is the problem here. Maybe you can just .Hide() mainwindow and then .Show() it after loading is completed. Or maybe it would be simpler if you showed a loading animation/whatever in mainwindow rather than a separate window. – Andy Nov 01 '19 at 15:00

1 Answers1

1

On your main window don't use the Application.Current.MainWindow instance, use this.Close() instead.

 private void Button_Click(object sender, RoutedEventArgs e)
    {
        LoadingWindow load = new LoadingWindow(...);
        Mouse.OverrideCursor = null;
        //Application.Current.MainWindow.Close();
        this.Close();
        load.ShowDialog();  //  Exception is here the next time it is called
    }

Refer to this thread & this for clarification on the difference.

SamTh3D3v
  • 9,854
  • 3
  • 31
  • 47