// 添加一个首选项命令
var preferences = new SettingsCommand("preferences", "Preferences", (handler) =>
{
var settings = new SettingsFlyout();
settings.Content = new PreferencesUserControl();
settings.HeaderBrush = new SolidColorBrush(_background);
settings.Background = new SolidColorBrush(_background);
settings.HeaderText = "Preferences";
settings.IsOpen = true;
});
6、显示超级按钮并选择设置超级按钮。
7、从设置窗格选择Preferences命令。
8、点击Remember where I was以启用切换开关。
9、取消设置窗格。
10、返回Visual Studio并停止调试。
11、按F5以再次启动应用程序。
12、转至首选项页面并确认切换开关被启用。
13、返回Visual Studio并停止调试。
练习3: 实现首选项
目前Contoso食谱每次启动时显示开始页面。在之前练习中添加名称为“Remember where I was”的用户首选项的目的是允许用户配置应用程序如何返回,即每次启动时转至上一次关闭时显示的页面。该用户首选项仅仅需要对代码进行细微的修改,因为Visual Studio已经在应用程序中包含当应用程序被挂起时保存导航状态的代码。 注意:进程生命周期管理是Windows应用商店应用的重要元素。当应用程序被挂起时,它可以在任何时候被操作系统终止。并且当应用程序被终止后,它的状态也将丢失。
用户不会因为暂时切换应用程序而去关心应用程序会丢失状态。这就是为什么Windows.UI.Xaml.Application类定义Suspending事件的原因。在应用被挂起前Suspending事件被触发。它为应用程序提供了保存状态的机会,以防止应用程序被操作系统终止并在之后被用户重新激活。触发事件的目的是当用户重新激活应用程序时能够恢复状态,以产生应用程序根本没有被终止的错觉。
Visual Studio在应用程序中包含一个名称为SuspensionManager的类。它位于项目Common文件夹的SuspensionManager.cs中。Visual Studio同时在App.xaml.cs的App构造函数中包含一行代码,它为Suspending事件注册了一个处理程序。该处理程序(OnSuspending)调用SuspensionManager.SaveAsync以保存应用程序的导航状态。导航状态包含用户查看的项或组,以及用户到达上述项或组的路径。
private async void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
await SuspensionManager.SaveAsync();
deferral.Complete();
}
此外Visual Studio在App.xaml.cs的OnLaunched方法中包含一个if子句,它负责当应用程序被挂起后又被操作系统终止时恢复应用程序的导航状态:
if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
// Restore the saved session state only when appropriate
await SuspensionManager.RestoreAsync();
}
所有这些工作的结果是您可以免费获得很多东西。如果Contoso食谱被挂起并终止,当重新启动时,它将自动转至您查看的最后页面。您可以通过在Visual Studio中按F5启动应用程序,选择某个食谱,并选择从Debug Location工具栏选择Suspend and shutdown以对它进行测试。
通过这种方式关闭应用程序后,按F5重新启动应用程序。上述步骤对应用程序被操作系统终止并被重新启动的过程进行了模拟。得益于Visual Studio的帮助,应用程序将返回至您关闭应用时查看的食谱。因为最近的应用程序历史也同时被恢复,您甚至可以使用后退按钮回溯在应用程序中的浏览步骤。
任务 1 –修改OnLaunched方法
Visual Studio已经包含当应用程序被挂起时保存导航状态以及如果被终止恢复状态的代码。我们将使用类似的策略以在应用程序被用户关闭后再次被启动且Remember where I was被启用时恢复导航状态。
1、打开App.xaml.cs并在靠近顶部处添加以下using语句。 C#
using Windows.Storage;
2、找到OnLaunched方法。紧靠await RecipeDataSource.LoadLocalDataAsync()语句后,添加以下语句。 C#
// If the app was closed by the user the last time it ran, and if "Remember
// "where I was" is enabled, restore the navigation state
if (args.PreviousExecutionState == ApplicationExecutionState.ClosedByUser)
{
if (ApplicationData.Current.RoamingSettings.Values.ContainsKey("Remember"))
{
bool remember = (bool)ApplicationData.Current.RoamingSettings.Values["Remember"];
if (remember)
await SuspensionManager.RestoreAsync();
}
}