How to save ObservableCollection in Windows Store App?

北战南征 提交于 2019-12-24 07:04:55

问题


I am creating Windows Store App based on Split App template. What is the best way to save data from SampleDataSource for later use?

I tried:

Windows.Storage.ApplicationDataContainer roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings;
roamingSettings.Values["Data"] = AllGroups;

It throws exception: 'Data of this type is not supported'.


回答1:


RoamingSettings only supports the runtime data types (with exception of Uri); additionally, there's a limitation as to how much data you can save per setting and in total.

You'd be better off using RoamingFolder (or perhaps LocalFolder) for the storage aspects.

For the serialization aspect you might try the DataContractSerializer. If you have a class like:

public class MyData
{
    public int Prop1 { get; set; }
    public int Prop2 { get; set; }
}
public ObservableCollection<MyData> coll;

then write as follows

var f = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("data.txt");
using ( var st = await f.OpenStreamForWriteAsync())
{
    var s = new DataContractSerializer(typeof(ObservableCollection<MyData>), 
                                       new Type[] { typeof(MyData) });
    s.WriteObject(st, coll);

and read like this

using (var st = await Windows.Storage.ApplicationData.Current.LocalFolder.OpenStreamForReadAsync("data.txt"))
{
    var t = new DataContractSerializer(typeof(ObservableCollection<MyData>), 
                                       new Type[] { typeof(MyData) });
    var col2 = t.ReadObject(st) as ObservableCollection<MyData>;

}


来源:https://stackoverflow.com/questions/13923600/how-to-save-observablecollection-in-windows-store-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!