1

How can I know which page I came from in a Windows phone 8.1? For example I have 3 pages: a Login page, a main page and a category page. What I want to do is to identify from which of those pages a user came to the main page; from the login page or from the category page.

I tried this code inside the OnNavigatedTo method in MainPage.cs,

var lastPage = this.Frame.BackStack.Last();           

if (lastPage != null && lastPage.SourcePageType.Name.ToString() == "LogInPage")
{               
}
else
{
}

But the thing is after I go to category page and return back to main page still it gives a login page as last stack. How to resolve that?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
SilentCoder
  • 1,970
  • 1
  • 16
  • 21

2 Answers2

1

Did you try removing the BackStack?

How to navigate using the back stack for Windows Phone 8

Or else try to cache the page.

How to cache a page in Windows Phone 8.1

Community
  • 1
  • 1
Kulasangar
  • 9,046
  • 5
  • 51
  • 82
1

But the thing is after I go to category page and return back to main page still it gives a login page as last stack. How to resolve that?

That's correct. When you navigate from the category page back to the main page by means of the hardware back button, the last entry on the back stack is popped off the back stack and pushed onto the end of the forward stack.

So, there's two different ways in which you can navigate to a page MainPage:

  1. You can navigate forward by means of Frame.Navigate(typeof(MainPage)), or Frame.GoForward() if MainPage is last in Frame.ForwardStack. The previous page that you were on is Frame.BackStack.Last().
  2. You can navigate backward by means of Frame.GoBack() if MainPage is last in Frame.BackStack. The previous page that you were on is Frame.ForwardStack.Last().

So, how do you know whether to consult the back stack or the forward stack? In your Page.OnNavigatedTo() method override, check the value of e.NavigationMode. If its value is NavigationMode.New or NavigationMode.Forward, then check the back stack. If its value is NavigationMode.Back, check the forward stack.

Here's some code:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    Type lastPage = null;

    switch (e.NavigationMode)
    {
        case NavigationMode.New:
        case NavigationMode.Forward:
            if (Frame.BackStack.Count > 0)
                lastPage = Frame.BackStack.Last().SourcePageType;
            break;

        case NavigationMode.Back:
            if (Frame.ForwardStack.Count > 0)
                lastPage = Frame.ForwardStack.Last().SourcePageType;
            break;

        default:
            // TODO
            break;
    }

    if (lastPage != null)
        System.Diagnostics.Debug.WriteLine("Last page was {0}", lastPage);
}
Decade Moon
  • 32,968
  • 8
  • 81
  • 101