如果我的应用程序被 Windows 终止(例如,如果它已暂停,但 Windows 需要释放内存以便抢占我的应用程序),当它重新启动时,会发生 OnLaunched() 事件,我可以测试它是否已终止(或者用户只是关闭它):
. . .
if ((args.PreviousExecutionState == ApplicationExecutionState.Terminated) ||
(args.PreviousExecutionState == ApplicationExecutionState.ClosedByUser))
{
}
. . .
如果终止,我想在上一个位置/页面恢复,而不是在初始页面(如果不同)。我怎样才能做到这一点?伪代码可能是:
if (CurrentPage != LastSavedPage)
{
CurrentPage = LastSavedPage;
// or: Frame.Navigate(typeof(LastSavedPage)
}
更新
所以这是我对我应该做的事情的看法,但我仍然“对此有疑问”(参见评论和代码)
// OnNavigateTo in each page:
Settings.Values["CurrentPageType"] = this.GetType();
Settings.Values["CurrentPageParam"] = args.Parameter;
//Will the line directly above work even if args.Parameter is empty, or must I do something like:
if (null != args.Parameters)
{
Settings.Values["CurrentPageParam"] = args.Parameter;
}
//OnLaunched in app.xaml.cs
if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
if ((localSettings.Values.ContainsKey("CurrentPageType")) &&
(localSettings.Values.ContainsKey("CurrentPageParam")))
{
rootFrame.Navigate((Type)localSettings.Values["CurrentPageType"],
localSettings.Values["CurrentPageParam"]);
}
}
更新 2
我收到此代码的异常:
ApplicationData.Current.LocalSettings.Values["CurrentPageType"] = this.GetType();
ApplicationData.Current.LocalSettings.Values["CurrentPageParam"] = args.Parameter;
mscorlib.dll 中出现“System.Exception”类型的异常,但未在用户代码中处理 WinRT 信息:尝试序列化要写入应用程序数据存储的值时出错附加信息:不支持此类型的数据。如果有这个异常的处理程序,程序可以安全地继续。
如果我将“.ToString()”附加到对 GetType() 的调用中,它不会爆炸......