0
class AppDataManager
{
    public static async Task SaveAsync<T>(T data, string fileName)
    {
        StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, 
            CreationCollisionOption.GenerateUniqueName);
        var stream = await file.OpenStreamForWriteAsync();
        var serializer = new DataContractSerializer(typeof(T));
        serializer.WriteObject(stream ,data);
        await stream.FlushAsync();
    }

    public static async Task<T> RestoreAsync<T>(string fileNa me)
    {
        try
        {
            var file = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);

            var instream = await file.OpenStreamForReadAsync();
            var serializer = new DataContractSerializer(typeof(T));
            return (T)serializer.ReadObject(instream);
        }
        catch (Exception)
        {
            return default(T);
        }
    }
}


    protected async override void OnNavigatedTo(NavigationEventArgs e)
    {
        await AskUserToLocalDataAsync();

        if (useLocalData)
        {
           SomethingGoesHere  = await AppDataManager.RestoreAsync<UserData>(fileName);
        }
    }

代码工作正常,但它只返回一个对象,我想编写多个对象并将其作为 observableCollection 检索以将其绑定到 GridView。GenerateUniqueName 是附加多个对象赖特?

怎么存放呢?以及如何检索它?

4

2 回答 2

0

创建一个具有将保存您的集合的属性的类。然后序列化该类。

于 2013-01-18T19:07:05.957 回答
0

我建议Collection为您的对象创建一个类。

例如一个Widget对象:

[DataContract]
public class Widget
{
  [DataMember]
  public string Name { get; set; }

  [DataMember]
  public int Value { get; set; }
}

然后你可以WidgetCollection上课:

[DataContract]
public class WidgetCollection
{
  [DataMember]
  public List<Widget> Widgets { get; set; }
}

您可以序列化/反序列化WidgetCollection,然后foreach通过并添加到ObservableCollection<Widget>.

IDisposable此外,将您的对象(如IRandomAccessStream)包装在using语句中,以便正确处理它们。

于 2013-01-18T19:13:32.687 回答