coolside
coolside

Reputation: 81

c# MVVM restart and main menu button

In my View folder I have MainWindow and GameWindow, in my ViewModel folder I have MainWindowViewModel and GameWindowViewModel. I'm trying from my GameWindowViewModel:

1) To restart my GameWindow on click with an ICommand and this function

void restartButtonClickFunction(object obj)
    {
        GameWindow gamewindow = new GameWindow();
        Application.Current.GameWindow.Close();
        gamewindow.Show();
    }

2) To go to my MainWindow again on click with an ICommand and the following function

void mainMenuButtonClickFunction(object obj)
    {
        MainWindow mainwindow = new MainWindow();
        Application.Current.GameWindow.Close();
        mainwindow.Show();
    }

It gives me errors and I can't figure out an other way. In my MainWindowViewModel I managed with the following function

void startButtonClickFunction(object obj)
    {
        GameWindow gamewindow = new GameWindow();
        Application.Current.MainWindow.Close();
        gamewindow.Show();
    }

Upvotes: 0

Views: 304

Answers (2)

coolside
coolside

Reputation: 81

it works for the MainMenu Button but when I try to restart the window with the following code the current Window closes but won't open again and gives the following error: An unhandled exception of type 'System.InvalidOperationException' occurred in PresentationFramework.dll

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

 void restartButtonClickFunction(object obj)
    {
        GameWindow gamewindow = new GameWindow();
        foreach (var window in Application.Current.Windows)
        {
            if (window is GameWindow)
            {
                ((Window)window).Close();
            }
        }
        gamewindow.Show();
    }

Upvotes: 0

Blinx
Blinx

Reputation: 400

Summary from comments:

Application.Current.MainWindow isn't a reference to your MainWindow class, it's a property on Application that indicates which Window is the 'Main' one, see https://msdn.microsoft.com/en-us/library/system.windows.application.mainwindow(v=vs.110).aspx.

This means that there isn't a property Application.Current.GameWindow.

Instead you could use Application.Current.Windows to get a collection of all the current Windows and then compare the type to get the one you want to close:

foreach (var window in Application.Current.Windows)
{
    if (window is GameWindow)
    {
        ((Window)window).Close();
    }
}

Alternatively, you could store the current Window in a property to allow you to easily close it

Upvotes: 1

Related Questions