如何在 Windows Store App 中保存 ObservableCollection? [英] How to save ObservableCollection in Windows Store App?

查看:25
本文介绍了如何在 Windows Store App 中保存 ObservableCollection?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在基于 Split App 模板创建 Windows 应用商店应用.从 SampleDataSource 保存数据以备后用的最佳方法是什么?

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

我试过了:

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

它抛出异常:'不支持这种类型的数据'.

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

推荐答案

RoamingSettings 仅支持 运行时数据类型(Uri除外);此外,每个设置和总共可以保存多少数据是有限制的.

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.

最好使用 RoamingFolder(或者可能是 LocalFolder) 用于存储方面.

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

对于序列化方面,您可以尝试 DataContractSerializer.如果您有这样的课程:

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;

然后写成如下

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

像这样阅读

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

}

这篇关于如何在 Windows Store App 中保存 ObservableCollection?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆