Fork me on GitHub

UWP-BackRequest

Week 1

啊,基础的事情都做完了,页面跳转这事情,很简单的,就是一个 Navigation,上一篇博客的时候就做完啦。但是,导航到了新页面,怎么回到原来的页面呢?这次就学习一下后退键把。

返回事件

说到后退事件,先不要着急动手。假设,我们的程序有上百个页面,各自之间可以灵活的跳转。那每一个页面都有后退事件,额,又回到了无人车事件了吗?可恶。不过,怎么会有这么蠢的事情嘛。仔细看看自己的UWP项目架构,我们可以发现 app.xaml.cs 文件。这个文件包含了重要的应用程序事件的事件处理程序,如启动、挂起和其他一些,且可被所有page共有。所以,这次回退事件的完成,我们要在 app.xaml.cs 文件中完成。

我们需要在文件中的 OnLaunched 函数加入如下语句:

1
2
3
4
5
6
7
8
9

...
//Add after rootFrame is defined
rootFrame.Navigated += OnNavigated;

...

//Add at the trail of the function
SystemNavigationManager.GetForCurrentView().BackRequested += BackRequested;

第一个语句注册导航事件,第二个语句注册后退事件。注册了事件,那么我们就需要定义事件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
private void OnNavigated(object sender, NavigationEventArgs e) {
//根据页面是否可以返回,在窗口显示返回按钮
SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = ((Frame)sender).CanGoBack ? AppViewBackButtonVisibility.Visible : AppViewBackButtonVisibility.Collapsed;
}

private void BackRequested(object sender, BackRequestedEventArgs e) {
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame == null) return;

//Navigate back if possible, and if the event has not already been handled .
if (!e.Handled && rootFrame.CanGoBack) {
e.Handled = true;
rootFrame.GoBack();
}
}

这样一来,程序就会在可以返回的时候,显示后退按钮并且返回上一个页面啦。

题外话:程序怎么知道返回哪个界面?A:程序页面跳转信息在堆栈中存储