Cronologia di spostamento e spostamento indietro per le app di Windows

API importanti: Evento BackRequested, Classe SystemNavigationManager, OnNavigatedTo

Le app di Windows offrono un sistema di spostamento uniforme basato sul pulsante Indietro che consente di ripercorrere la cronologia di spostamento dell'utente all'interno di un'app e, a seconda del dispositivo in uso, tra app diverse.

Per implementare lo spostamento indietro nella tua app, inserisci un pulsante Indietro nell'angolo superiore sinistro dell'interfaccia utente dell'app. L'utente si aspetta che il pulsante Indietro passi alla posizione precedente nella cronologia di navigazione dell'app. Tieni presente che spetta a te decidere quali azioni di spostamento aggiungere alla cronologia di spostamento e come rispondere alla selezione del pulsante Indietro.

Per la maggior parte delle app con più pagine, è consigliabile usare il controllo NavigationView per fornire il framework di spostamento per l'app. Si adatta a un'ampia gamma di dimensioni dello schermo e supporta entrambi gli stili di spostamento: superiore e a sinistra. Se l'app usa il controllo NavigationView, puoi usare il pulsante Indietro predefinito di NavigationView.

Nota

Le linee guida e gli esempi in questo articolo devono essere usati quando si implementa la navigazione senza usare il NavigationView controllo . Se si usa NavigationView, queste informazioni forniscono informazioni di base utili, ma è consigliabile usare le linee guida e gli esempi specifici nell'articolo NavigationView

Pulsante Back

Per creare un pulsante Indietro, usa il controllo Button con lo stile NavigationBackButtonNormalStyle e inserisci il pulsante nell'angolo superiore sinistro dell'interfaccia utente dell'app. Per i dettagli vedi gli esempi di codice XAML qui sotto.

Back button in the top left of the app's UI

<Page>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <Button x:Name="BackButton"
                Style="{StaticResource NavigationBackButtonNormalStyle}"
                IsEnabled="{x:Bind Frame.CanGoBack, Mode=OneWay}" 
                ToolTipService.ToolTip="Back"/>

    </Grid>
</Page>

Se l'app ha un controllo CommandBar superiore, il controllo Button, la cui altezza è di 44 epx, non risulterà perfettamente allineato ai controlli AppBarButton, la cui altezza è di 48 epx. Per evitare questa incoerenza, allinea la parte superiore del controllo Button entro i 48 epx.

Back button on top command bar

<Page>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        
        <CommandBar>
            <CommandBar.Content>
                <Button x:Name="BackButton"
                        Style="{StaticResource NavigationBackButtonNormalStyle}"
                        IsEnabled="{x:Bind Frame.CanGoBack, Mode=OneWay}" 
                        ToolTipService.ToolTip="Back" 
                        VerticalAlignment="Top"/>
            </CommandBar.Content>
        
            <AppBarButton Icon="Delete" Label="Delete"/>
            <AppBarButton Icon="Save" Label="Save"/>
        </CommandBar>
    </Grid>
</Page>

Per ridurre al minimo lo spostamento degli elementi dell'interfaccia utente nell'app, mostra un pulsante Indietro disabilitato quando il backstack è vuoto (IsEnabled="{x:Bind Frame.CanGoBack, Mode=OneWay}"). Se però prevedi che l'app non avrà mai un backstack, non c'è bisogno di mostrare il pulsante Indietro.

Back button states

Ottimizzare per dispositivi e input diversi

Queste linee guida per la progettazione dello spostamento indietro sono applicabili a tutti i dispositivi, ma gli utenti potranno trarre vantaggio se si ottimizzano per diversi fattori di forma e metodi di input.

Per ottimizzare l'interfaccia utente:

  • Desktop/Hub: disegna il pulsante Indietro in-app nell'angolo superiore sinistro dell'interfaccia utente dell'app.
  • Tablet Mode: un pulsante Indietro hardware o software può essere presente nei tablet, ma consigliamo di disegnare un pulsante Indietro in-app per maggiore chiarezza.
  • Xbox/TV: non disegnare un pulsante Indietro per evitare di ingombrare inutilmente l'interfaccia utente. Sfrutta invece la funzionalità del pulsante B del game pad per tornare indietro.

Se l'app verrà eseguita sulla Xbox, crea un trigger di visualizzazione personalizzato per Xbox per attivare o disattivare la visibilità del pulsante. Se usi un controllo NavigationView abiliterà o disabiliterà automaticamente la visibilità del pulsante Indietro se l'app è in esecuzione su Xbox.

È consigliabile gestire gli eventi seguenti (oltre al pulsante Indietro Clic) per supportare gli input più comuni per lo spostamento indietro.

Event Input
CoreDispatcher.AcceleratorKeyActivated ALT+freccia sinistra,
VirtualKey.GoBack
SystemNavigationManager.BackRequested Windows + tasto Backspace,
Pulsante B Gamepad,
Pulsante Indietro in modalità tablet,
Pulsante Indietro hardware
CoreWindow.PointerPressed VirtualKey.XButton1
(come il pulsante Indietro trovato su alcuni topi.

Esempi di codice

In questa sezione viene illustrato come gestire lo spostamento indietro usando un'ampia gamma di input.

Pulsante Indietro e spostamento indietro

È necessario gestire almeno l'evento pulsante Click Indietro e fornire il codice per eseguire lo spostamento indietro. È anche consigliabile disabilitare il pulsante Indietro quando il backstack è vuoto.

Questo esempio di codice seguente mostra come implementare il comportamento di spostamento indietro con un pulsante Indietro. Il codice risponde all'evento Button Click da esplorare. Il pulsante Indietro è abilitato o disabilitato nel metodo OnNavigatedTo , che viene chiamato quando si passa a una nuova pagina.

Il codice viene visualizzato per MainPage, ma questo codice viene aggiunto a ogni pagina che supporta lo spostamento indietro. Per evitare la duplicazione, è possibile inserire il codice correlato alla navigazione nella App classe nella App.xaml.* pagina code-behind.

<!-- MainPage.xaml -->
<Page x:Class="AppName.MainPage">
...
        <Button x:Name="BackButton" Click="BackButton_Click"
                Style="{StaticResource NavigationBackButtonNormalStyle}"
                IsEnabled="{x:Bind Frame.CanGoBack, Mode=OneWay}" 
                ToolTipService.ToolTip="Back"/>
...
<Page/>

Code-behind:

// MainPage.xaml.cs
private void BackButton_Click(object sender, RoutedEventArgs e)
{
    App.TryGoBack();
}

// App.xaml.cs
//
// Add this method to the App class.
public static bool TryGoBack()
{
    Frame rootFrame = Window.Current.Content as Frame;
    if (rootFrame.CanGoBack)
    {
        rootFrame.GoBack();
        return true;
    }
    return false;
}
// MainPage.h
namespace winrt::AppName::implementation
{
    struct MainPage : MainPageT<MainPage>
    {
        MainPage();
 
        void MainPage::BackButton_Click(IInspectable const&, RoutedEventArgs const&)
        {
            App::TryGoBack();
        }
    };
}

// App.h
#include "winrt/Windows.UI.Core.h"
#include "winrt/Windows.System.h"
#include "winrt/Windows.UI.Input.h"
#include "winrt/Windows.UI.Xaml.Input.h"
 
using namespace winrt;
using namespace Windows::Foundation;
using namespace Windows::UI::Core;
using namespace Windows::UI::Input;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;

struct App : AppT<App>
{
    App();

    // ...

    // Perform back navigation if possible.
    static bool TryGoBack()
    {
        Frame rootFrame{ nullptr };
        auto content = Window::Current().Content();
        if (content)
        {
            rootFrame = content.try_as<Frame>();
            if (rootFrame.CanGoBack())
            {
                rootFrame.GoBack();
                return true;
            }
        }
        return false;
    }
};

Supportare le chiavi di accesso

Il supporto della tastiera è fondamentale per garantire che le applicazioni funzionino in modo ottimale per gli utenti con competenze, capacità e aspettative diverse. È consigliabile supportare i tasti di scelta rapida per lo spostamento avanti e indietro, perché gli utenti che si basano su di essi si aspettano entrambi. Per altre info, vedi Interazioni da tastiera e tasti di scelta rapida.

I tasti di scelta rapida comuni per lo spostamento avanti e indietro sono ALT+Freccia DESTRA (avanti) e ALT+Freccia SINISTRA (indietro). Per supportare questi tasti per lo spostamento, gestire l'evento CoreDispatcher.AcceleratorKeyActivated . Gestisci un evento che si trova direttamente nella finestra (anziché un elemento nella pagina) in modo che l'app risponda ai tasti di scelta rapida indipendentemente dall'elemento con stato attivo.

Aggiungere il codice alla App classe per supportare i tasti di scelta rapida e lo spostamento in avanti, come illustrato di seguito. Si presuppone che il codice precedente per supportare il pulsante Indietro sia già stato aggiunto. È possibile visualizzare tutto il App codice insieme alla fine della sezione Esempi di codice.

// App.xaml.cs
// Add event handler in OnLaunced.
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
    // ...
    // Do not repeat app initialization when the Window already has content,
    // just ensure that the window is active
    if (rootFrame == null)
    {
        // ...
        // rootFrame.NavigationFailed += OnNavigationFailed;

        // Add support for accelerator keys. 
        // Listen to the window directly so the app responds
        // to accelerator keys regardless of which element has focus.
        Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated +=
            CoreDispatcher_AcceleratorKeyActivated;

        // ...

    }
}

// ...

// Add this code after the TryGoBack method added previously.
// Perform forward navigation if possible.
private bool TryGoForward()
{
    Frame rootFrame = Window.Current.Content as Frame;
    if (rootFrame.CanGoForward)
    {
        rootFrame.GoForward();
        return true;
    }
    return false;
}

// Invoked on every keystroke, including system keys such as Alt key combinations.
// Used to detect keyboard navigation between pages even when the page itself
// doesn't have focus.
private void CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher sender, AcceleratorKeyEventArgs e)
{
    // When Alt+Left are pressed navigate back.
    // When Alt+Right are pressed navigate forward.
    if (e.EventType == CoreAcceleratorKeyEventType.SystemKeyDown
        && (e.VirtualKey == VirtualKey.Left || e.VirtualKey == VirtualKey.Right)
        && e.KeyStatus.IsMenuKeyDown == true
        && !e.Handled)
    {
        if (e.VirtualKey == VirtualKey.Left)
        {
            e.Handled = TryGoBack();
        }
        else if (e.VirtualKey == VirtualKey.Right)
        {
            e.Handled = TryGoForward();
        }
    }
}
// App.cpp
void App::OnLaunched(LaunchActivatedEventArgs const& e)
{
    // ...
    // Do not repeat app initialization when the Window already has content,
    // just ensure that the window is active
    if (rootFrame == nullptr)
    {
        // ...
        // rootFrame.NavigationFailed({ this, &App::OnNavigationFailed });

        // Add support for accelerator keys. 
        // Listen to the window directly so the app responds
        // to accelerator keys regardless of which element has focus.
        Window::Current().CoreWindow().Dispatcher().
            AcceleratorKeyActivated({ this, &App::CoreDispatcher_AcceleratorKeyActivated });

        // ...
    }
}

// App.h
struct App : AppT<App>
{
    App();

    // ...
    // Add this code after the TryGoBack method added previously.

private:
    // Perform forward navigation if possible.
    bool TryGoForward()
    {
        Frame rootFrame{ nullptr };
        auto content = Window::Current().Content();
        if (content)
        {
            rootFrame = content.try_as<Frame>();
            if (rootFrame.CanGoForward())
            {
                rootFrame.GoForward();
                return true;
            }
        }
        return false;
    }
 
 
    // Invoked on every keystroke, including system keys such as Alt key combinations.
    // Used to detect keyboard navigation between pages even when the page itself
    // doesn't have focus.
    void CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher const& /* sender */, AcceleratorKeyEventArgs const& e)
    {
        // When Alt+Left are pressed navigate back.
        // When Alt+Right are pressed navigate forward.
        if (e.EventType() == CoreAcceleratorKeyEventType::SystemKeyDown
            && (e.VirtualKey() == Windows::System::VirtualKey::Left || e.VirtualKey() == Windows::System::VirtualKey::Right)
            && e.KeyStatus().IsMenuKeyDown
            && !e.Handled())
        {
            if (e.VirtualKey() == Windows::System::VirtualKey::Left)
            {
                e.Handled(TryGoBack());
            }
            else if (e.VirtualKey() == Windows::System::VirtualKey::Right)
            {
                e.Handled(TryGoForward());
            }
        }
    }
};

Gestire le richieste back di sistema

I dispositivi Windows offrono vari modi in cui il sistema può passare una richiesta di spostamento indietro all'app. Alcuni modi comuni sono il pulsante B in un game pad, il tasto Windows + tasto Backspace o il pulsante Indietro del sistema in modalità Tablet; le opzioni esatte disponibili dipendono dal dispositivo.

È possibile supportare le richieste di risposta fornite dal sistema hardware e software registrando un listener per l'evento SystemNavigationManager.BackRequested .

Ecco il codice aggiunto alla App classe per supportare le richieste back fornite dal sistema. Si presuppone che il codice precedente per supportare il pulsante Indietro sia già stato aggiunto. È possibile visualizzare tutto il App codice insieme alla fine della sezione Esempi di codice.

// App.xaml.cs
// Add event handler in OnLaunced.
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
    // ...
    // Do not repeat app initialization when the Window already has content,
    // just ensure that the window is active
    if (rootFrame == null)
    {
        // ...
        // Add support for accelerator keys. 
        // ... (Previously added code.)

        // Add support for system back requests. 
        SystemNavigationManager.GetForCurrentView().BackRequested 
            += System_BackRequested;

        // ...

    }
}

// ...
// Handle system back requests.
private void System_BackRequested(object sender, BackRequestedEventArgs e)
{
    if (!e.Handled)
    {
        e.Handled = TryGoBack();
    }
}
// App.cpp
void App::OnLaunched(LaunchActivatedEventArgs const& e)
{
    // ...
    // Do not repeat app initialization when the Window already has content,
    // just ensure that the window is active
    if (rootFrame == nullptr)
    {
        // ...
        // Add support for accelerator keys. 
        // ... (Previously added code.)

        // Add support for system back requests. 
        SystemNavigationManager::GetForCurrentView().
            BackRequested({ this, &App::System_BackRequested });

        // ...
    }
}

// App.h
struct App : AppT<App>
{
    App();

    // ...

private:
    // ...

    // Handle system back requests.
    void System_BackRequested(IInspectable const& /* sender */, BackRequestedEventArgs const& e)
    {
        if (!e.Handled())
        {
            e.Handled(TryGoBack());
        }
    }
};

Comportamento di spostamento indietro di sistema per la compatibilità con le versioni precedenti

In precedenza, le app UWP usavano SystemNavigationManager.AppViewBackButtonVisibility per mostrare o nascondere un pulsante Indietro di sistema per lo spostamento indietro. (Questo pulsante genera un Evento SystemNavigationManager.BackRequested . Questa API continuerà a essere supportata per garantire la compatibilità con le versioni precedenti, ma non è più consigliabile usare il pulsante Indietro esposto da AppViewBackButtonVisibility. Devi invece fornire il pulsante Indietro in-app come descritto in questo articolo.

Se si continua a usare AppViewBackButtonVisibility, l'interfaccia utente di sistema eseguirà il rendering del pulsante Indietro di sistema all'interno della barra del titolo. L'aspetto e le interazioni utente del pulsante Indietro sono rimasti invariati dalle build precedenti.

Title bar back button

Gestire i pulsanti di spostamento del mouse

Alcuni mouse forniscono pulsanti di spostamento hardware per lo spostamento avanti e indietro. Puoi supportare questi pulsanti del mouse gestendo l'evento CoreWindow.PointerPressed e controllando IsXButton1Pressed (indietro) o IsXButton2Pressed (avanti).

Ecco il codice aggiunto alla classe per supportare lo App spostamento del pulsante del mouse. Si presuppone che il codice precedente per supportare il pulsante Indietro sia già stato aggiunto. È possibile visualizzare tutto il App codice insieme alla fine della sezione Esempi di codice.

// App.xaml.cs
// Add event handler in OnLaunced.
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
    // ...
    // Do not repeat app initialization when the Window already has content,
    // just ensure that the window is active
    if (rootFrame == null)
    {
        // ...
        // Add support for system back requests. 
        // ... (Previously added code.)

        // Add support for mouse navigation buttons. 
        Window.Current.CoreWindow.PointerPressed += CoreWindow_PointerPressed;

        // ...

    }
}

// ...

// Handle mouse back button.
private void CoreWindow_PointerPressed(CoreWindow sender, PointerEventArgs e)
{
    // For this event, e.Handled arrives as 'true'.
    if (e.CurrentPoint.Properties.IsXButton1Pressed)
    {
        e.Handled = !TryGoBack();
    }
    else if (e.CurrentPoint.Properties.IsXButton2Pressed)
    {
        e.Handled = !TryGoForward();
    }
}
// App.cpp
void App::OnLaunched(LaunchActivatedEventArgs const& e)
{
    // ...
    // Do not repeat app initialization when the Window already has content,
    // just ensure that the window is active
    if (rootFrame == nullptr)
    {
        // ...
        // Add support for system back requests. 
        // ... (Previously added code.)

        // Add support for mouse navigation buttons. 
        Window::Current().CoreWindow().
            PointerPressed({ this, &App::CoreWindow_PointerPressed });

        // ...
    }
}

// App.h
struct App : AppT<App>
{
    App();

    // ...

private:
    // ...

    // Handle mouse forward and back buttons.
    void CoreWindow_PointerPressed(CoreWindow const& /* sender */, PointerEventArgs const& e)
    {
        // For this event, e.Handled arrives as 'true'. 
        if (e.CurrentPoint().Properties().IsXButton1Pressed())
        {
            e.Handled(!TryGoBack());
        }
        else if (e.CurrentPoint().Properties().IsXButton2Pressed())
        {
            e.Handled(!TryGoForward());
        }
    }
};

Tutto il codice aggiunto alla classe App

// App.xaml.cs
//
// (Add event handlers in OnLaunched override.)
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
    // ...
    // Do not repeat app initialization when the Window already has content,
    // just ensure that the window is active
    if (rootFrame == null)
    {
        // ...
        // rootFrame.NavigationFailed += OnNavigationFailed;

        // Add support for accelerator keys. 
        // Listen to the window directly so the app responds
        // to accelerator keys regardless of which element has focus.
        Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated +=
            CoreDispatcher_AcceleratorKeyActivated;

        // Add support for system back requests. 
        SystemNavigationManager.GetForCurrentView().BackRequested 
            += System_BackRequested;

        // Add support for mouse navigation buttons. 
        Window.Current.CoreWindow.PointerPressed += CoreWindow_PointerPressed;

        // ...

    }
}

// ...

// (Add these methods to the App class.)
public static bool TryGoBack()
{
    Frame rootFrame = Window.Current.Content as Frame;
    if (rootFrame.CanGoBack)
    {
        rootFrame.GoBack();
        return true;
    }
    return false;
}

// Perform forward navigation if possible.
private bool TryGoForward()
{
    Frame rootFrame = Window.Current.Content as Frame;
    if (rootFrame.CanGoForward)
    {
        rootFrame.GoForward();
        return true;
    }
    return false;
}

// Invoked on every keystroke, including system keys such as Alt key combinations.
// Used to detect keyboard navigation between pages even when the page itself
// doesn't have focus.
private void CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher sender, AcceleratorKeyEventArgs e)
{
    // When Alt+Left are pressed navigate back.
    // When Alt+Right are pressed navigate forward.
    if (e.EventType == CoreAcceleratorKeyEventType.SystemKeyDown
        && (e.VirtualKey == VirtualKey.Left || e.VirtualKey == VirtualKey.Right)
        && e.KeyStatus.IsMenuKeyDown == true
        && !e.Handled)
    {
        if (e.VirtualKey == VirtualKey.Left)
        {
            e.Handled = TryGoBack();
        }
        else if (e.VirtualKey == VirtualKey.Right)
        {
            e.Handled = TryGoForward();
        }
    }
}

// Handle system back requests.
private void System_BackRequested(object sender, BackRequestedEventArgs e)
{
    if (!e.Handled)
    {
        e.Handled = TryGoBack();
    }
}

// Handle mouse back button.
private void CoreWindow_PointerPressed(CoreWindow sender, PointerEventArgs e)
{
    // For this event, e.Handled arrives as 'true'.
    if (e.CurrentPoint.Properties.IsXButton1Pressed)
    {
        e.Handled = !TryGoBack();
    }
    else if (e.CurrentPoint.Properties.IsXButton2Pressed)
    {
        e.Handled = !TryGoForward();
    }
}


// App.cpp
void App::OnLaunched(LaunchActivatedEventArgs const& e)
{
    // ...
    // Do not repeat app initialization when the Window already has content,
    // just ensure that the window is active
    if (rootFrame == nullptr)
    {
        // ...
        // rootFrame.NavigationFailed({ this, &App::OnNavigationFailed });

        // Add support for accelerator keys. 
        // Listen to the window directly so the app responds
        // to accelerator keys regardless of which element has focus.
        Window::Current().CoreWindow().Dispatcher().
            AcceleratorKeyActivated({ this, &App::CoreDispatcher_AcceleratorKeyActivated });

        // Add support for system back requests. 
        SystemNavigationManager::GetForCurrentView().
            BackRequested({ this, &App::System_BackRequested });

        // Add support for mouse navigation buttons. 
        Window::Current().CoreWindow().
            PointerPressed({ this, &App::CoreWindow_PointerPressed });

        // ...
    }
}

// App.h
#include "winrt/Windows.UI.Core.h"
#include "winrt/Windows.System.h"
#include "winrt/Windows.UI.Input.h"
#include "winrt/Windows.UI.Xaml.Input.h"
 
using namespace winrt;
using namespace Windows::Foundation;
using namespace Windows::UI::Core;
using namespace Windows::UI::Input;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;

struct App : AppT<App>
{
    App();

    // ...

    // Perform back navigation if possible.
    static bool TryGoBack()
    {
        Frame rootFrame{ nullptr };
        auto content = Window::Current().Content();
        if (content)
        {
            rootFrame = content.try_as<Frame>();
            if (rootFrame.CanGoBack())
            {
                rootFrame.GoBack();
                return true;
            }
        }
        return false;
    }
private:
    // Perform forward navigation if possible.
    bool TryGoForward()
    {
        Frame rootFrame{ nullptr };
        auto content = Window::Current().Content();
        if (content)
        {
            rootFrame = content.try_as<Frame>();
            if (rootFrame.CanGoForward())
            {
                rootFrame.GoForward();
                return true;
            }
        }
        return false;
    }
  
    // Invoked on every keystroke, including system keys such as Alt key combinations.
    // Used to detect keyboard navigation between pages even when the page itself
    // doesn't have focus.
    void CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher const& /* sender */, AcceleratorKeyEventArgs const& e)
    {
        // When Alt+Left are pressed navigate back.
        // When Alt+Right are pressed navigate forward.
        if (e.EventType() == CoreAcceleratorKeyEventType::SystemKeyDown
            && (e.VirtualKey() == Windows::System::VirtualKey::Left || e.VirtualKey() == Windows::System::VirtualKey::Right)
            && e.KeyStatus().IsMenuKeyDown
            && !e.Handled())
        {
            if (e.VirtualKey() == Windows::System::VirtualKey::Left)
            {
                e.Handled(TryGoBack());
            }
            else if (e.VirtualKey() == Windows::System::VirtualKey::Right)
            {
                e.Handled(TryGoForward());
            }
        }
    }

    // Handle system back requests.
    void System_BackRequested(IInspectable const& /* sender */, BackRequestedEventArgs const& e)
    {
        if (!e.Handled())
        {
            e.Handled(TryGoBack());
        }
    }

    // Handle mouse forward and back buttons.
    void CoreWindow_PointerPressed(CoreWindow const& /* sender */, PointerEventArgs const& e)
    {
        // For this event, e.Handled arrives as 'true'. 
        if (e.CurrentPoint().Properties().IsXButton1Pressed())
        {
            e.Handled(!TryGoBack());
        }
        else if (e.CurrentPoint().Properties().IsXButton2Pressed())
        {
            e.Handled(!TryGoForward());
        }
    }
};

Linee guida per il comportamento di spostamento indietro personalizzato

Se si sceglie di fornire uno spostamento back stack personalizzato, l'esperienza deve essere coerente con altre app. È consigliabile seguire i modelli seguenti per le azioni di spostamento:

Azione di spostamento Aggiungi alla cronologia di spostamento?
Da pagina a pagina, gruppi di peer diversi

In questa illustrazione, l'utente passa dal livello 1 dell'app al livello 2, attraversando i gruppi peer, in modo che lo spostamento venga aggiunto alla cronologia di navigazione.

Diagram of navigation across peer groups showing the user navigating from group one to group two and the back to group one.

Nella figura successiva, l'utente si sposta tra due gruppi di peer allo stesso livello, attraversando nuovamente i gruppi peer, in modo che lo spostamento venga aggiunto alla cronologia di spostamento.

Diagram of navigation across peer groups showing the user navigating from group one to group two then on to group three and back to group two.

Da pagina a pagina, stesso gruppo di peer, nessun elemento di spostamento sullo schermo

L'utente passa da una pagina a un'altra con lo stesso gruppo di peer. Non c'è nessun elemento di spostamento sullo schermo (come NavigationView) che consenta lo spostamento diretto su entrambe le pagine.

Nell'illustrazione seguente l'utente si sposta tra due pagine nello stesso gruppo di peer e lo spostamento dovrebbe essere aggiunto alla cronologia di spostamento.

Navigation within a peer group

Da pagina a pagina, stesso gruppo di peer, con un elemento di spostamento sullo schermo

L'utente passa da una pagina a un'altra con lo stesso gruppo di peer. Entrambe le pagine sono visualizzate nello stesso elemento di spostamento, come NavigationView.

Dipende

Sì, aggiungi alla cronologia di spostamento, con due eccezioni significative. Se prevedi che gli utenti della tua app si spostino spesso tra le pagine nel gruppo di peer o se vuoi mantenere la gerarchia di spostamento, non aggiungere alla cronologia di spostamento. In questo caso, quando l'utente preme Indietro, torna all'ultima pagina visitata prima di passare al gruppo peer corrente.

Navigation across peer groups when a navigation element is present

Visualizzare un'interfaccia utente temporanea

L'app visualizza una finestra popup o figlio, ad esempio una finestra di dialogo, una schermata iniziale o una tastiera su schermo oppure l'app entra in una modalità speciale, ad esempio la modalità di selezione multipla.

No

Quando l'utente preme il pulsante Indietro, chiudere l'interfaccia utente temporanea (nascondere la tastiera sullo schermo, annullare la finestra di dialogo e così via) e tornare alla pagina che ha generato l'interfaccia utente temporanea.

Showing a transient UI

Enumerare gli elementi

L'app visualizza il contenuto di un elemento sullo schermo, ad esempio i dettagli per l'elemento selezionato nell'elenco/dettagli.

No

L'enumerazione degli elementi è simile allo spostamento all'interno di un gruppo di peer. Quando l'utente preme indietro, passare alla pagina che precede la pagina corrente con l'enumerazione dell'elemento.

Iterm enumeration

Ripresa in corso

Quando l'utente passa a un'altra app e torna all'app, ti consigliamo di tornare all'ultima pagina nella cronologia di spostamento.