How to save ObservableCollection in Windows Store

2019-08-13 17:54发布

问题:

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>;

}