Unexpected URI parameters on Windows Phone back button

Let’s assume your Windows Phone App contains several code snippets that all navigate to the same page, sometimes passing some URI parameters to it and sometimes not. In the page’s OnNavigatedTo method, you parse the URI to retrieve the expected parameter and do whatever you want with it, for example display a message to the user if a specific parameter was contained in the URI:

override void OnNavigatedTo(NavigationEventArgs e)
{
	Uri uri = e.Uri;
	// Parse URI to retrieve parameter and do something with it...
}

Now, you navigate to another page, do something there, and return to our main page by pressing the hardware back button. Of course, you’ll again end up in the OnNavigatedTo method. And once again, you’ll end up having the message displayed, although this time you certaintly did not set the above-mentioned parameter that triggers the message! What happened?

When navigating to any page for the first time, the page is instantiated and the URI that was passed to the NavigationService is stored “as it is”, meaning with or without parameters, depending on if you passed some to the URI or not. Now, if you navigate to that page again, this time not specifying the URI but using NavigationService.GoBack() or the hardware back button, the URI originally stored is not overwritten – if it contained parameters, these are still existent. By parsing the URI again, you stumble into the same procedure as before (the message displayed to the user), because also the URI is the same as before.

The solution is simple: Check if your coming back from another page in the OnNavigatedTo handler – if yes, there is no point in even looking at the URI since it won’t have changed:

override void OnNavigatedTo(NavigationEventArgs e)
{
	if (e.NavigationMode != System.Windows.Navigation.NavigationMode.Back)
	{
		Uri uri = e.Uri;
		// Parse URI to retrieve parameter and do something with it...
	}
}