let's add a back button to our second page.
<Page
x:Class="pc.NavigateExample.SecondPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBlock>Second
Page</TextBlock>
<TextBox x:Name="output_TextBox" PlaceholderText="Parameter received" />
<Button x:Name="Back_Button" Click="Back_Button_Click">Back</Button>
</StackPanel>
</Grid>
</Page>
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace pc.NavigateExample
{
public sealed partial class SecondPage : Page
{
public SecondPage() { this.InitializeComponent(); }
protected override void
OnNavigatedTo(NavigationEventArgs e) {
var parameter = e.Parameter as string;
if (parameter != null)
output_TextBox.Text =
parameter;
}
private void
Back_Button_Click(object sender,
Windows.UI.Xaml.RoutedEventArgs e)
{
if(Frame.CanGoBack)
Frame.GoBack();
}
}
}
Now our base "Page" object has a Frame property that can be used for navigation, so let's leverage it to go back to our main page. This however is a very rudimentary implementation of back navigation, there's all sorts of complexities that we haven't even broached, like for example "Windows key" + Backspace shortcut for navigating back. Luckily there is the SystemNavigationManager class to make our lives easier.
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace pc.NavigateExample
{
public sealed partial class SecondPage : Page
{
public SecondPage() {
this.InitializeComponent();
SystemNavigationManager.GetForCurrentView().BackRequested +=
SecondPage_BackRequested;
}
protected override void
OnNavigatedTo(NavigationEventArgs e) {
var parameter = e.Parameter as string;
if (parameter != null)
output_TextBox.Text =
parameter;
}
protected override void
OnNavigatedFrom(NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
SystemNavigationManager.GetForCurrentView().BackRequested -=
SecondPage_BackRequested;
}
private void
SecondPage_BackRequested(object sender, BackRequestedEventArgs e){
if(!e.Handled && Frame.CanGoBack)
Frame.GoBack();
}
private void
Back_Button_Click(object sender, RoutedEventArgs e)
{
if (Frame.CanGoBack)
Frame.GoBack();
}
}
}
- "Windows Key" + Backspace
- Hardware back button
- Keyboard back button
- mouse back button