Once you have created your project based on the WPF App (.NET Framework) template, follow these steps to add pages to your project and integrate them with the NavigationService:
- Right-click on the project node where you want to create the pages.
- As shown in this screenshot, navigate to Add | Page... from the context menu:
- This will open the following Add New Item dialog window, where the item titled Page (WPF) is already selected. Give it a name, Page1.xaml and click Add. It will create the Page1.xaml and the associated code-behind file Page1.xaml.cs in your project:
- Now follow the same steps, 1 to 3, to create another page Page2.xaml, which will add both the XAML and associated C# code-behind file into the project.
- Open the Page1.xaml file and replace the Grid with the following XAML:
<Grid> <TextBlock Text="This is Page 1" FontSize="20" HorizontalAlignment="Center" VerticalAlignment="Center"/> <Button Content="Next" Height="30" Width="120" Margin="20" HorizontalAlignment="Right" VerticalAlignment="Bottom" Click="OnNextButtonClicked"/> </Grid>
- In the associated code-behind file (Page1.xaml.cs), add the following button-click event handler:
private void OnNextButtonClicked(object sender,
RoutedEventArgs e) { NavigationService.Navigate(new Uri("Page2.xaml",
UriKind.Relative)); }
- Similarly, add the following XAML into the Page2.xaml page, replacing the existing Grid:
<Grid> <TextBlock Text="This is Page 2" FontSize="20" HorizontalAlignment="Center" VerticalAlignment="Center"/> <Button Content="Previous" Height="30" Width="120" Margin="20" HorizontalAlignment="Right" VerticalAlignment="Bottom" Click="OnPreviousButtonClicked"/> </Grid>
- Add the following button-click event handler into the Page2.xaml.cs file:
private void OnPreviousButtonClicked(object sender, RoutedEventArgs e) { if (NavigationService.CanGoBack) { NavigationService.GoBack(); } }
- Now open the MainWindow.xaml file and replace the XAML content with the following:
<NavigationWindow x:Class="CH01.PageDemo.MainWindow" xmlns=
"http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525" Source="Page1.xaml"> </NavigationWindow>
- Now open the MainWindow.xaml.cs file and change its base class to NavigationWindow, instead of Window.
- Run the application, which will open the following screen containing Page 1:
- Clicking on the Next button will navigate you to Page 2, as shown here, which contains the activated navigational button automatically provided by the WPF Framework:
- Now, if you click on the Previous button or the back button in the navigation panel, it will navigate you to Page 1.