Search code examples
c#windows-phone-7windows-phone-8windows-phonewindows-phone-8.1

How to go to previous page in windows phone 8 when back button is pressed


I have a home page or landing page in my windows phone c# based app where user enters login details and upon successful login user is redirected to page2 . Here the user will see a list box with few items . Upon selecting an item from this list box a new page called "Threadx" opens.(where x is the each page that opens upon clicking the x item in the list box)

While user is on this Thread page "Threadx" he may receive the toast notifications and the thread gets updated with new replies or answers on that thread.

But When user clicks on back button the "ThreadX" page doesn't get closed and instead it goes to its previous state where it has less number of messages , and so on until the app gets closed.

protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);
        if (e.NavigationMode == NavigationMode.Back)
        {
            return;
        }
    }

I would like to know if this "Threadx" page can be closed upon clicking back button without affecting other "Threadx+1","Threadx+2"..."Threadx+n" pages.

Any help would be really appreciated.


Solution

  • Normally windows keeps the pages on it's stack when you leave a page and navigate to another page. If you want to navigate to the previous page on pressing the Back Button you can do following things:

    Add following line to OnNavigatedTo method:

    Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;
    

    Add definition for HardwareButtons_BackPressed method:

        private void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
        {
            e.Handled = true;
            if (Frame.CanGoBack)
                Frame.GoBack();
        }
    

    Don't forget to add Windows.Phone.UI.Input to the namespace list.