2017-04-17 52 views
0

我试图在UWP应用程序挂起时使用Prism保存对象,以便在恢复或启动时恢复它们。当应用程序的挂起事件触发并且在Resume和LaunchApplicationAsync上检索对象时,正在进行保存。UWP Prism SessionStateService在用户关闭后丢失状态

当我在调试中使用Visual Studio Suspend和Resume时,对象被正确恢复,但是当我自己执行Suspend and 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); 
    } 

回答

0

原因是ViewLocation类型不是已知类型,所以它不能被序列化并且s tored。您必须使用RegisterKnownType方法SessionsStateService将其添加到已知类型的列表中,或者将其自己序列化为简单类型,如string

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

+0

我已将ViewLocation添加到已知类型。这是一个复杂的类型,但我认为它应该串行化原始属性,忽略未知的类型中定义的对象?即使这种情况已被破坏(因为ViewLocation上的属性不能被序列化)应该使用[RestorableState]保存原语不起作用? – fralama