Bhargavi Reddy
Bhargavi Reddy

Reputation: 61

How to go previous page when hardware back button pressed in windows phone 8.1?

I am creating somany pages in windows phone app.How to go previous page when back button pressed.when I am clcik back button it will go to first page.

for example I am in 4th page. whenever I cilck backbutton I want to go to 3rd page but it go to 1st page. Iam using below code.

public selectbus()
    {
        this.InitializeComponent();


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

    }

    void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
    {
        Frame rootFrame = Window.Current.Content as Frame;
        if (rootFrame != null && rootFrame.CanGoBack)
        {
             rootFrame.GoBack();
            e.Handled = true;


        }
    }

please anyone help me.

Upvotes: 0

Views: 706

Answers (2)

Igor Kulman
Igor Kulman

Reputation: 16361

Subscribe to the BackPressed event in App.xaml.cs and nowhere else. Take a look at the accepted answer here Windows Phone 8.1 Universal App terminates on navigating back from second page?.

Upvotes: 0

faflo10
faflo10

Reputation: 386

First, check if you navigate as the following (from page1 to page2, for example) :

this.Frame.Navigate(typeof(NameOfYourPage));

Then, on the page you want to add the HardwareButtons_BackPressed, check you have the following lines :

using Windows.UI.Xaml;
using Windows.Phone.UI.Input;

then, your code should look like the following :

//In constructor
HardwareButtons.BackPressed += HardwareButtons_BackPressed;

//Later in code
void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
{
    Frame frame = Window.Current.Content as Frame;
    if (frame == null)
    {
        return;
    }
    if (frame.CanGoBack)
    {
        frame.GoBack();
        e.Handled = true;
    }
}

This works for me, it should work for you as well !

Upvotes: 1

Related Questions