Iiridayn
Iiridayn

Reputation: 1821

UWP on screen back button - how to trigger system back event?

I have a UWP app - the design has a "Back" button in the screen content, which I would like to use to trigger the system navigation event handled in my App.xaml.cs file. My current click handler, which is pasted to each file which needs it is:

Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame.CanGoBack)
    rootFrame.GoBack();

How would I instead trigger the back event, which would trigger the back event handler which already contains this code?

Upvotes: 1

Views: 988

Answers (1)

David Grochocki
David Grochocki

Reputation: 680

In App.xaml.cs, add this to OnLaunced(...):

protected override void OnLaunched(LaunchActivatedEventArgs e)
{
    ...
    if (rootFrame == null)
    {
        ...
        // Register a handler for BackRequested events
        SystemNavigationManager.GetForCurrentView().BackRequested += this.OnBackRequested;
    }
    ...
}

Where in OnBackRequested(...), which can also be in App.xaml.cs:

private void OnBackRequested(object sender, BackRequestedEventArgs e)
{
    Frame rootFrame = Window.Current.Content as Frame;

    if (rootFrame.CanGoBack)
    {
        e.Handled = true;
        rootFrame.GoBack();
    }
}

This could easily be adapted to support multiple frames if you implement any custom navigation, and you can also add global handling of showing/hiding the back button via something like:

public void UpdateBackButton(Frane frame)
{
    bool canGoBack = (frame?.CanGoBack ?? false);

    SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = canGoBack
        ? AppViewBackButtonVisibility.Visible
        : AppViewBackButtonVisibility.Collapsed;
}

You can programmatically call back via a function like this in App.xaml.cs or in a custom navigation manager:

public bool TryGoBack(Frame frame)
{
    bool handled = false;

    if (frame?.CanGoBack ?? false)
    {
        handled = true;
        frame.GoBack();
    }

    this.UpdateBackButton(frame);

    return handled;
}

Upvotes: 0

Related Questions