【问题标题】:UWP Prism SessionStateService loses state after closed by userUWP Prism SessionStateService 在被用户关闭后丢失状态
【发布时间】:2017-09-12 20:52:45
【问题描述】:

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

当我在调试中使用 Visual Studio Suspend 和 Resume 时,对象会正确恢复,但在我自己执行 Suspend 和 Shutdown 或关闭应用程序时不会。带有 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);
    }

【问题讨论】:

    标签: c# mvvm uwp prism


    【解决方案1】:

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

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

    【讨论】:

    • 我已将 ViewLocation 添加到已知类型。它是一种复杂类型,但我认为它应该序列化原始属性,忽略未在已知类型中定义的对象?即使它被破坏了(因为 ViewLocation 上的属性不能被序列化)应该用 [RestorableState] 保存原语不起作用吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-13
    • 2021-04-01
    • 2019-12-16
    • 2022-12-12
    • 2018-03-22
    相关资源
    最近更新 更多