Saad
Saad

Reputation: 195

C# - Changing From MainWindow to Another Page in MVVM Format WPF Application

I have been trying to figure out how to switch from my MainWindow.xaml to a WPF Page in my View folder called StudentView.xaml when a button on the MainWindow is clicked.

This is what I have so far...

private void ButtonStartQuiz_Click(object sender, RoutedEventArgs e) {
    var window = new View.StudentView();
}

All I want is for the MainWindow to switch to the StudentView page when the user clicks the button. I've tried opening the StudentView as a new Window, but I don't want a new window every time the user clicks a button. I've tried googling and looking at other posts, but I don't understand how I'm supposed to implement them. Please help!

Upvotes: 3

Views: 1226

Answers (3)

AnjumSKhan
AnjumSKhan

Reputation: 9827

If you want to keep your MainWindow.xaml content's state alive, then use Frame + Pages.

Otherwise, use ContentControl and use ContentTemplateSelector .

Upvotes: 0

J. Hasan
J. Hasan

Reputation: 512

After the button click then, you can create an instance of that page and set the instance as content of your mainwindow.

     private NavigatingPageName Instance;
     private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (Instance == null) 
            {
                Instance = new  NavigatingPageName();
            }
            this.Content = Instance;
        }

Upvotes: 1

omginput
omginput

Reputation: 69

If you want to navigate from MainPage.xaml to another .xaml use:

            NAMEOFYOURCURRENTFRAME.Navigate(typeof(PAGENAME));

If you want to navigate from a page which isn´t MainPage.xaml to another .xaml use:

        var rootFrame = Window.Current.Content as Frame;
        var mainPage = rootFrame.Content as MainPage;
        rootFrame.Navigate(typeof(PAGETONAVIGATETO));

Upvotes: 0

Related Questions