I want to do something when the user clicks the hardware button on the phone. I have two pages. In the App.xaml.cs I've added the following code to handling the navigation to and from the pages.
SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested;
private void OnBackRequested(object sender, BackRequestedEventArgs e)
{
if (this.Frame.CanGoBack)
this.Frame.GoBack();
}
But now I want to do something else when the user clicks the back button. How can I do that?
If you want the back button to do something different on each page, then you will need to handle the Back button on each page - I do this to prompt the user to confirm losing their changes on one of my pages.
Subscribe to the BackRequested event in each page's OnNavigatedTo method:
protected override void OnNavigatedTo(Windows.UI.Xaml.Navigation.NavigationEventArgs e)
{
SystemNavigationManager.GetForCurrentView().BackRequested += this.OnBackPressed;
base.OnNavigatedTo(e);
}
And make sure you unsubscribe in the page's OnNavigatedFrom method:
protected override void OnNavigatingFrom(Windows.UI.Xaml.Navigation.NavigatingCancelEventArgs e)
{
SystemNavigationManager.GetForCurrentView().BackRequested -= this.OnBackPressed;
base.OnNavigatingFrom(e);
}
Now you can write a OnBackPressed() event handler on each page that does what you want it to do on that page.