简体   繁体   中英

How to save ObservableCollection in Windows Store App?

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'.

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM