Change between pages in WPF

ioan picture ioan · Jul 24, 2014 · Viewed 30.6k times · Source

I want to make a layout like the one used in any website - the header, sidebar and footer stay the same but the center part. I have multiple pages/windows to show in a wpf blend C# application and they are totally different. For example, stackoverflow has a layout for the homepage and another one for each Question. Here's another exemple:

first  page second page

I had to do that in a previous project and I used a single grid layout and then, for each page, I had to hide() all of them and show that each one on top -

What's the trick? How can I do the same thing in a wpf application? In a typical C# application I would have to open a child window each time but that seems ugly these days.

Thank you in advance!

Answer

Sheridan picture Sheridan · Jul 24, 2014

If you are going to use Pages in WPF, then you will need to read the Navigation Overview page on MSDN. In short however, you can navigate between Pages in a WPF Application by using the NavigationService Class. To change the page from code behind, you could do something like this:

NextPage page = new NextPage();
NavigationService.Navigate(page);

To let the users change the Page, you can use the Hyperlink Class in your Pages:

<Hyperlink NavigateUri="pack://application:,,,/AppName;component/Pages/NextPage.xaml">
    Navigate to Next Page
</Hyperlink>

To get your desired page setup, you will have to load your Pages into a Frame, which you can then layout wherever you like in MainWindow.xaml:

<Frame Source="pack://application:,,,/AppName;component/Pages/SomePage.xaml" />