Reputation: 9
I'm creating a UWP app in C#. I'm trying to run different blocks of code within my OnNavigatedTo function depending on what page sent me there. Right now I have if else statements determining which blocks of code are ran depending on what page sent me to the page I'm on now.
My existing code is shown below:
protected override void OnNavigatedTo(NavigationEventArgs e)
//runs every time MainPage is Navigated to from another page or when program is first started and MainPage loads
{
if ([SomeAttribute == Page2])
{
//attempt to add string from page[2] to List
if (e.Parameter is string && !string.IsNullOrWhiteSpace((string)e.Parameter) && !InspectorInst.Names_list.Contains(e.Parameter))
//if thing passed from previous page (e.Parameter) is a string and isnt null or whitespace and isnt already in the Names_list
{
string s = e.Parameter.ToString();//create string to hold e.Parameter
this.InspectorInst.Names_list.Add(s);//Add string to Names_list
}
}
else{
//do something else
}
base.OnNavigatedTo(e);
}
[SomeAttribute == Page2] should be something that will return true if the page that directed me to the page I'm currently on was Page2. And SomeAttribute would return the page that sent me to the page I'm currently on. I have not been able to find anything in the UWP documentation that would accomplish this.
If am going about this problem the wrong way and there is an easier way to accomplish this, what would that be?
Thanks
Upvotes: 0
Views: 383
Reputation: 2475
I think that if you want a page to have a different behavior depending on where it is called, the normal way would be to pass different values as the second parameter to the Navigate method.
If you absolutely want to know which page has called, then you can examine the last entry in the navigation stack, like this:
var entry = this.Frame.BackStack.LastOrDefault();
if (entry != null)
// Check entry.SourcePageType - it contains the type of the previous page
Note that you may also have to check the NavigationEventArgs.NavigationMode to see if the user is going back from the page or not.
Upvotes: 2