user3911053
user3911053

Reputation:

Back Button Running Amok

On each of my app pages I am setting the back button's functionality, since I want it to do different things each time. However, when I run this on one page:

SystemNavigationManager.GetForCurrentView().BackRequested += (s, a) =>
{
    Frame.Navigate(typeof(MainPage));
    a.Handled = true;
};

It also runs the back button's function on another one of my pages if that page has been visited first. This throws an exception, since it tries to unload a nonexistent project. Is this not the correct way to set the back button's functionality per page?

Upvotes: 1

Views: 115

Answers (1)

sibbl
sibbl

Reputation: 3219

This is the correct behavior as SystemNavigationManager.GetForCurrentView() returns the same SystemNavigationManager as it's still the same view (not page!) and you then have two event handlers attached to the event.

If you want to have specific event handlers per page, use OnNavigatedTo to add and OnNavigatedFrom to remove the event handler:

public class BackButtonPage : Page
{
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        BackButtonVisibility = base.Frame.CanGoBack ? AppViewBackButtonVisibility.Visible : AppViewBackButtonVisibility.Collapsed;

        SystemNavigationManager.GetForCurrentView().BackRequested += BackButtonPage_BackRequested;

        base.OnNavigatedTo(e);
    }

    protected override void OnNavigatedFrom(NavigationEventArgs e)
    {
        base.OnNavigatedFrom(e);

        SystemNavigationManager.GetForCurrentView().BackRequested -= BackButtonPage_BackRequested;
    }

    private void BackButtonPage_BackRequested(object sender, BackRequestedEventArgs e)
    {
        OnBackRequested(sender, e);
    }

    protected virtual void OnBackRequested(object sender, BackRequestedEventArgs e)
    {
        //your page specific code here
        Frame.Navigate(typeof(MainPage));
        e.Handled = true;
    }

    public AppViewBackButtonVisibility BackButtonVisibility
    {
        get { return SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility; }
        set { SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = value; }
    }
}

(source from Microsoft's examples on github)

Upvotes: 3

Related Questions