问题
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?
回答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:
- You can navigate forward by means of
Frame.Navigate(typeof(MainPage))
, orFrame.GoForward()
if MainPage is last inFrame.ForwardStack
. The previous page that you were on isFrame.BackStack.Last()
. - You can navigate backward by means of
Frame.GoBack()
if MainPage is last inFrame.BackStack
. The previous page that you were on isFrame.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);
}
回答2:
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
来源:https://stackoverflow.com/questions/26794353/identify-from-which-page-come-to-this-page-in-windows-phone-8-1