2013-01-18 110 views
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是追加多個對象賴特?序列化多個對象

如何存儲它?以及如何檢索它?

+2

不要吞下例外 – SLaks

回答

0

創建一個包含屬性的類,該屬性將保存您的集合。然後序列化該類。

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聲明中,以便它們得到正確處置。