[英]How to serialize an observablecollection of type entity to xml
[英]How to serialize an ObservableCollection of custom type
我正在尝试将自定义类型的ObservableCollection保存到wp8应用程序中的隔离存储中。 可观察的集合包含BitmapImage类型和字符串类型的值。 这样做的目的是从CameraCaptureTask结果中保存图像及其各自的名称。
void cameraCaptureTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
//clear current values if any
imgChosenPhotoFileName = null;
bmp = new BitmapImage();
imgChosenPhotoFileName = e.OriginalFileName;
//Display the photo on the page
bmp.SetSource(e.ChosenPhoto);
imgChosenPhoto.Source = bmp;
//Add photo info to Recent
AddToImgList(imgChosenPhotoFileName, bmp);
}
}
private void AddToImgList(string fileName, BitmapImage bitmap)
{
Settings.imageList.Value.Add(new ImageItem() { ImageName = fileName, ImageUri = bitmap });
//Settings.imageList.Value.Add(bitmap);
//populate the List with the saved imageList
imgList.ItemsSource = Settings.imageList.Value;
}
其中Settings是我已声明的类,用于保存名为imageList的可观察集合,而imgList是将observablecollection绑定到的列表框。
Settings.cs
public static class Settings
{
public static readonly Setting<ObservableCollection<ImageItem>> imageList = new Setting<ObservableCollection<ImageItem>>("imageList", new ObservableCollection<ImageItem>());
}
设置是用于从隔离存储中保存和加载数据的类。
Setting.cs
public class Setting<T>
{
string name;
T value;
T defaultValue;
bool hasValue;
public Setting(string name, T defaultValue)
{
this.name = name;
this.defaultValue = defaultValue;
}
public T Value
{
get
{
//Check for the cached value
if (!this.hasValue)
{
//Try to get the value from Isolated Storage
if (!IsolatedStorageSettings.ApplicationSettings.TryGetValue(this.name, out this.value))
{
//It hasn't been set yet
this.value = this.defaultValue;
IsolatedStorageSettings.ApplicationSettings[this.name] = this.value;
}
this.hasValue = true;
}
return this.value;
}
set
{
//Save the value to Isolated Storage
IsolatedStorageSettings.ApplicationSettings[this.name] = value;
this.value = value;
this.hasValue = true;
}
}
public T DefaultValue
{
get { return this.defaultValue; }
}
// Clear cached value
public void ForceRefresh()
{
this.hasValue = false;
}
}
此外,可观察的集合的类型为ImageItem,如下所示
ImageItem.cs
public class ImageItem
{
public BitmapImage ImageUri
{
get;
set;
}
public string ImageName
{
get;
set;
}
}
由于某些原因,尽管在应用程序运行时,图片保存在imageList集合中,并填充在imgList列表框中,但是当应用程序关闭并重新启动时,observablecollection是否为空? 我相信是BitmapImage的问题(未序列化?),我无法获得可观察的集合来从CameraCaptureTask保存图像吗?
在您的代码中,我已经看到您正在使用IsolatedStorage类。 我真的不知道如何使用IsolatedStorage类,但是我怀疑给它分配了一个变量
IsolatedStorageSettings.ApplicationSettings[this.name] = this.value;
不会进行将值保存到变量的设置。 我进行了快速搜索,并在msdn中找到了保存方法,也许可以帮上忙。
但是,您可以缩小问题范围,仅使用IsolatedStorageSettings以获得更好的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.