3
votes

Quite a simple question I guess, but I can't seem to figure it out..

I have a MainPage.xaml that runs code on the OnNavigatedTo event. How can I disable this if the user used the hardware backkey to navigate to this page?

MainPage => Page2 USES THE HW BACKKEY => MainPage.xaml // DO NOT RUN THE CODE

MainPage => Page3 => MainPage.xaml // RUN THE CODE

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    if (!TheUserNavigatedBackFromAnotherPageUsingTheBackkey)
    {
        // RUN FRESH CODE
    }
    else
    {
        // DO NOTHING
    }  
}

Kind regards, Niels

2

2 Answers

10
votes

You can check the NavigationMode of NavigationEventArgs.

if (e.NavigationMode == NavigationMode.Back)
{

 // navigation is going backward in the stack

}

This means that the navigation is going backward in the stack, but doesn't necessarily mean that the back button was pressed. By calling the Frame.GoBack() method for example, it would still be navigating backward.

2
votes

If you navigate back not only with backkey, and you want to check if it was pressed, then hence subscribing to HardwareButtons.BackPressed is app-wide, it should be easy to provide a flag, which you can set. Let's create app-wide flag:

public sealed partial class App : Application
{
    public bool wasBackKeyUsed = false;
     // rest of the code

Then you have to check how your backward navigation is performed, there are few ways it can be done:

  • if you are using NavigationHelper (Common/NavigationHelper.cs) then open that file and will see where it subscribes. In the eventhandler of backkey, set the flag just before executing the command:

    (Application.Current as App).wasBackKeyUsed = true; // set the flag
    this.GoBackCommand.Execute(null); // execute going back
    
  • if you are handling your backkey yourself and/or in App.xaml.cs via template project (this answer may help a little), then set the flag just before Frame.GoBack();:

    (Application.Current as App).wasBackKeyUsed = true; // set the flag
    Frame.GoBack(); // go back
    

Once you have your flag, you can use it like this to check whether back key was used for navigation:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    //check if BackKeyWas used:
    if((Application.Current as App).wasBackKeyUsed)
    {
        // do some code
        // and remember to restet the flag
        (Application.Current as App).wasBackKeyUsed = false;
    }