How to handle back button pressed for UWP

自闭症网瘾萝莉.ら 提交于 2019-12-01 08:27:25

you can use BackRequested event to handle back request:

SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested;

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

Little bit explained answer. You can used SystemNavigationManager of Windows.UI.Core namespace

For Single Page


If you just want to handle navigation for single page. Follow the following steps

Step 1. Use namespace Windows.UI.Core

using Windows.UI.Core;

Step 2. Register back request event for current view. Best place for this is main constructor of class after InitializeComponent().

public MainPage()
{
    this.InitializeComponent();
    //register back request event for current view
    SystemNavigationManager.GetForCurrentView().BackRequested += MainPage_BackRequested;
}

Step 3. Handle BackRequested event

private void Food_BackRequested(object sender, BackRequestedEventArgs e)
{
    if (Frame.CanGoBack)
    {
        Frame.GoBack();
        e.Handled = true;
    }
}

For Complete Application at one place for single rootFrame


Best place for handling all backbutton for all Views is App.xaml.cs

Step 1. Use namespace Windows.UI.Core

using Windows.UI.Core;

Step 2. Register back request event for current view. Best place for this is OnLaunched just before Window.Current.Activate

protected override void OnLaunched(LaunchActivatedEventArgs e)
{
    ...
    SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested;
    Window.Current.Activate();
}

Step 3. Handle BackRequested event

private void OnBackRequested(object sender, BackRequestedEventArgs e)
{
    Frame rootFrame = Window.Current.Content as Frame;
    if (rootFrame.CanGoBack)
    {
        rootFrame.GoBack();
        e.Handled = true;
    }
}

References- Handle back button pressed in UWP

Hope this is helpful to someone!

Dilip Jangid

The above code is exactly correct but you have to add object of frame in rootFrame variable. Below are given:

private Frame _rootFrame;
 protected override void OnLaunched(LaunchActivatedEventArgs e)
 { 
        Frame rootFrame = Window.Current.Content as Frame;
        if (Window.Current.Content==null)
        {
            _rootFrame = new Frame();
        }
}

And pass this _rootFrame to OnBackRequested method. Like:

 private void OnBackRequested(object sender, BackRequestedEventArgs 
 {
       if (_rootFrame.CanGoBack)
       {
            _rootFrame.GoBack();
            e.Handled = true;
       }
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!