0

我需要将什么属性保存到 RoamingSettings?

就像我序列化数据时一样,它需要 aDataContractDataMember属性。我可以将我的类序列化为 XML,但我需要将其保存为RoamingSettings

roamingSettings.Values["MyType"] = _mytype;

调试时,我收到以下错误消息:

不支持这种类型的数据。
WinRT 信息:尝试序列化要写入应用程序数据存储的值时出错

我想我需要一个属性,但是哪个?

4

2 回答 2

4

使用正确的 StorageFolder ApplicationData.Current.RoamingFolder

public static class RoamingStorage<T> {

    public static async void SaveData(string filename, T data)
    {
        try
        {
            StorageFile file = await ApplicationData.Current.RoamingFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
            using (IRandomAccessStream raStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                using (IOutputStream outStream = raStream.GetOutputStreamAt(0))
                {
                    DataContractSerializer serializer = new DataContractSerializer(typeof(List<Item>));
                    serializer.WriteObject(outStream.AsStreamForWrite(), data);
                    await outStream.FlushAsync();
                }
            }
        }
        catch (Exception exc)
        {
            throw exc;
        }
    }

    public static async System.Threading.Tasks.Task<T> LoadData(string filename)
    {
        T data = default(T);
        try
        {
            StorageFile file = await ApplicationData.Current.RoamingFolder.GetFileAsync(filename);
            using (IInputStream inStream = await file.OpenSequentialReadAsync())
            {
               DataContractSerializer serializer = new DataContractSerializer(typeof(T));
               data = (T)serializer.ReadObject(inStream.AsStreamForRead());
            }
        }
        catch (FileNotFoundException ex)
        {
            throw ex;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return data;
    }
}

示例调用

RoamingStorage<List<Item>>.SaveData(FILENAME,Items);

List<Item> data = await RoamingStorage<List<Item>>.LoadData(FILENAME);
于 2012-06-26T07:45:47.073 回答
1

处理这种情况的最佳方法是将对象序列化为字符串并存储它。

将存储的字符串值反序列化为目标对象。

于 2012-04-24T19:21:34.597 回答