WPF Page Navigation


WPF offers a way to set up pages for your application. What do I mean by that and how do you do that? First, create a WPF application in Visual Studio. Suppose you want to have two pages of content for your application. The content will take up almost all of the surface area of your application. The user will click on buttons to take them immediately to Page1 or Page2. In a real project, you might use more descriptive names than Page1 and Page2.

Below is the project’s appearance after I replicated it from the video and make some minor changes, such as the background colors of the pages.

WPF Page Navigation

Below is the XAML. Notice that the container of the pages is a Frame. Also, we have removed the Navigation Bar with this property setting in the Frame “NavigationUIVisibility=”Hidden“.

<Window x:Class="PagesSimple.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:PagesSimple"
        mc:Ignorable="d" WindowStartupLocation="CenterScreen"
        Title="PagesSimple" Height="250" Width="400" MinWidth="260" MinHeight="150">
    <Grid>
        <StackPanel Orientation="Horizontal" Height="35" VerticalAlignment="Top" Margin="0,0,0,0">
            <Button Name="Btn1" Content="Page 1" MinWidth="100" Click="Btn1_Click"/>
            <Button Name="Btn2" Content="Page 2" MinWidth="100" Margin="10,0,0,0" Click="Btn2_Click"/>
        </StackPanel>
        <Frame x:Name="MainFrame" Margin="1,35,1,1" NavigationUIVisibility="Hidden"/>
    </Grid>
</Window>

using System.Windows;
namespace PagesSimple
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void Btn1_Click(object sender, RoutedEventArgs e)
        {
            // create a new instance of the page and assign it
            MainFrame.Content = new Page1();
        }
        private void Btn2_Click(object sender, RoutedEventArgs e)
        {
            MainFrame.Content = new Page2();
        }
    }
}

The pages are very simple. They are just placeholders for our example. Here is the partial listing Xaml for Page1.

    <Grid Background="Azure">
        <TextBlock FontWeight="Bold" FontSize="24" HorizontalAlignment="Center" 
                   VerticalAlignment="Center">Page 1</TextBlock>
    </Grid>

Learn from YouTube

If you learn well from videos, there is a good one at YouTube that describes this process quite well. The video is C# WPF and GUI – Pages and Navigation.