Reputation: 116
I followed MS examples at the letter but I still encounter an odd issue. Let me explain it :)
My app has 3 pages. Main, Add and Help. Main allows to go to Add with a .Navigate with args. Add allows to go to Help with a .Navigate without args. Add allows to go back to Main with either the backbutton or a cancel button (the cancel button is using the GoBack()). Help can only go back to Add using the backbutton.
My code is pretty simple on the main page to define the back request :
In the OnNavigatedTo() :
SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
SystemNavigationManager.GetForCurrentView().BackRequested += MainPage_BackRequested;
The event Handler :
private void MainPage_BackRequested(object sender, BackRequestedEventArgs e)
{
if (this.Frame.CanGoBack)
{
this.Frame.GoBack();
e.Handled = true;
}
}
My issue is the following :
When debugging, the backstack is OK. But when I hit my issue, the BackRequested event Handler is indeed call twice (twice because I hit the "CanGoBack == false" I presume), like it's stuck in a loop. Any idea ?
Thanks.
Upvotes: 1
Views: 217
Reputation: 116
and first of all, thanks @mm8 and @AVK. You were right, it was the event registering many times. But the removing the Handler before adding it again was indeed not working in my case (and I don't understand why AT ALL, as the debugger show it was going through the "-=" but not really removing it thus looping once more every time I went back to the mainpage.
So, I followed the advice of Martin Zikmund from the @AVK question (here) as it looked so much cleaner. Instead of just adding the event Handler at the end of the OnLaunched (basically, if you launched the app again when it was already running, you register yet another Handler), I added it the in if(rootFrame == null){ part. That way it seems to work pretty well.
It's a shame every piece of advice MS gives on handling the backbutton is pretty wrong don't you think ?
Upvotes: 2
Reputation: 169160
Make sure that you only hook up a single event handler to the event. You can try to remove any previous one using the -=
syntax:
SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
var nav = SystemNavigationManager.GetForCurrentView();
nav.BackRequested -= MainPage_BackRequested; //remove any event handler
nav.BackRequested += MainPage_BackRequested;
Upvotes: 1