UWP Prism SessionStateService在用户关闭后丢失状态

时间:2017-04-17 08:42:20

标签: c# mvvm uwp prism

当我的UWP应用程序暂停时,我正在尝试使用Prism保存对象,以便在恢复或启动时可以恢复它们。当应用程序的Suspending事件触发并且正在Resume和LaunchApplicationAsync上检索对象时,正在进行保存。

当我在调试中使用Visual Studio Suspend and Resume时,对象会正确恢复,但在我执行暂停和关闭或自己关闭应用程序时则不能。对于具有RestorableState注释的基本属性,行为是相同的。

当应用程序在关机后启动时,我只能在SessionState字典中看到一个项目(" AppFrame" - 看起来像是由Prism插入),所以看起来字典会被重置。我需要做些什么特别的事情来保存超出Suspended状态的值(即当它被用户终止或关闭时)?

以下是App.xaml.cs的启动方法:

    protected override Task OnLaunchApplicationAsync(LaunchActivatedEventArgs e)
    {
        ApplicationView.GetForCurrentView().TryEnterFullScreenMode();

        RootPageViewModel.ShellNavigation(typeof(SurveyListPage));

        RootPageViewModel.RestorePropertyStates();

        return Task.FromResult(true);
    }

还原RestorePropertyStates方法:

    public void RestorePropertyStates()
    {

        if (SessionStateService.SessionState.ContainsKey(nameof(CurrentLocation)))
        {
            CurrentLocation = SessionStateService.SessionState[nameof(CurrentLocation)] as ViewLocation;
        }
    }

还有保存属性的方法:

    public void SavePropertyStates()
    {
        if (SessionStateService.SessionState.ContainsKey(nameof(CurrentLocation)))
        {
            SessionStateService.SessionState.Remove(nameof(CurrentLocation));
        }
        SessionStateService.SessionState.Add(nameof(CurrentLocation), CurrentLocation);
    }

1 个答案:

答案 0 :(得分:0)

原因是ViewLocation类型不是已知类型,因此无法序列化和存储。您必须使用RegisterKnownType上的SessionsStateService方法将其添加到已知类型列表中,或者将其自行序列化为类似string的简单类型。

我通常在会话状态之上创建一个层,使用Json.NET库将所有复杂类型序列化为JSON字符串,这减轻了必须记住添加已知类型的新类型的负担:-)。