次の方法で共有


How to add support for the back button in the TitleBar - XAML

No doubt that if you've spent any time with Windows 10 and the 1st party apps you may have noticed the back button in the TitleBar:

 

You can incorporate this into your Windows 10 UWP app with a few simple changes.  Likely, you have already have similar code in place to support a Back Button in UI but why lose that real estate when you can put it in the TitleBar?

To test this out, I downloaded the Windows 10 UWP samples from GitHub: https://github.com/Microsoft/Windows-universal-samples

In many of the samples, pick a XAML sample, there is a NavigationHelper.cs class.  In this class I made a few changes detailed below.

1. Obtain a reference to the current SystemNavigationManager in the sample NavigationHelper or in your own page frame navigation code:

privateSystemNavigationManager systemNavManager = Windows.UI.Core.SystemNavigationManager.GetForCurrentView();

In the constructor of the NavigationHelper class (in your app it would be your nav helper class),  I hook the SystemNavigationManager BackRequested event

if (systemNavManager != null)

{

    systemNavManager.BackRequested += SystemNavManager_BackRequested;

}

2. Add the event handler:

privatevoid SystemNavManager_BackRequested(object sender, BackRequestedEventArgs e)

{

    this.GoBack();

  e.Handled = true; // Important to set to true for phone to prevent the OS from also navigating back.

}

  

3. You need to manage the Back Button visibility, for example when on your home page.  This code, checks  the size of the back stack:

privatevoid UpdateBackButtonVisibility(int BackStackDepth)

{

    if (systemNavManager != null)

    {

         if (BackStackDepth > 0)

        {

            systemNavManager.AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;

        }

        else

       {

            systemNavManager.AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;

       }

    }

}

4. Finally, the code calls the UpdateBackButtonVisibility method in both OnNavigatedTo and OnNavigatedFrom in the sample NavigationHelper.cs file that I am working with.  You could also hook into Navigated as well if that works better for your code.  here's the first few lines of OnNavigatedTo with the call:

publicvoid OnNavigatedTo(NavigationEventArgs e)

{

    var frameState = SuspensionManager.SessionStateForFrame(this.Frame);

    this._pageKey = "Page-" + this.Frame.BackStackDepth;

    // Update visibility of tile bar back button

    UpdateBackButtonVisibility(this.Frame.BackStackDepth);

    if (e.NavigationMode == NavigationMode.New)

   {

5. Put similar code in OnNavigatedFrom if using the sample code and that's it!  Now you can remove the Back Button from your content UI.   One note regarding Mobile.  This code works fine for mobile as long as you set e.handled = true in the BackRequested event as shown above.