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);
}
}
代码工作正常,但它只返回一个Object,我想编写多个对象并将其作为observableCollection检索以将其绑定到GridView。 GenerateUniqueName是追加多个对象吗?
如何存放?以及如何检索它?
答案 0 :(得分:0)
创建一个具有保存集合的属性的类。然后序列化该类。
答案 1 :(得分: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
语句中,以便妥善处理。