0
votes

I am developing an app in windows phone 7.8 which opens a webpage in it. I have to navigate inside that page.

I want that while pressing the back button, it goes back inside that webpage but each time I press it, the app closes.

How can I modify the behaviour of that button? Is it possible?

2

2 Answers

2
votes

In WP7, you can't access the control's navigation history, so you may well need to implement it yourself. I'd porobably do something like this.

1 Handle the navigated event in the control, and each time you visit a page, push the Uri onto a stack of Uris.
2 On the back key press, if there is more than 1 Uri in the stack (i.e. more than the initially loaded page) navigate to the previous URI (since we can't go back, fake it by navigating forward to the previous page...)
3 If we are at the first entry in the stack, let the system handle the button press.

public MainPage()
{
    InitializeComponent();
    WB1.Navigated += WB1_Navigated;
}

Stack<Uri> visitedUrls = new Stack<Uri>();

void WB1_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
    visitedUrls.Push(e.Uri);
}

protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
    if (visitedUrls.Count > 1)
    {
        WB1.Navigate(visitedUrls.Pop());
        e.Cancel = true;
    }
}

Note that this is far from perfect, and won't handle form resubmissions, for example.

In WP8, you would check whether the browser's navigation stack allows you to go back. If it does, go back and cancel the button press. If not, let the system handle the back button for you.

protected override void OnBackKeyPress(ComponentModel.CancelEventArgs e)
{
    if (myBrowserInstance.CanGoBack)
    {
        myBrowserInstance.GoBack();
        e.Cancel = true;
    }
}
1
votes

Remember to Cancel the event call in this way:

protected override void OnBackKeyPress(ComponentModel.CancelEventArgs e)
{
    // your code 

     e.Cancel = true; 
}

As ARM suggested, be careful when using this. According to Microsoft, if you press the back key, when you are in the first page, the app must close. So do not use this override on the first page.