简体   繁体   中英

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!

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));

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;
        }

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

Otherwise, use ContentControl and use ContentTemplateSelector .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM