我正在嘗試將自定義類型的ObservableCollection保存到我的wp8應用程序中的獨立存儲中。可觀察的集合保存類型BitmapImage和字符串的值。這樣做的目的是從CameraCaptureTask結果中保存圖像及其各自的名稱。如何序列化ObservableCollection的自定義類型
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;
}
位置設置爲我宣佈舉行命名的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的圖像?
你可以加載你的加載/保存代碼到你的問題?這似乎是問題的根源... – 2013-03-15 01:22:39
根據我的經驗,ObservableCollection應該與列表沒有任何不同。我懷疑問題出在你的保存/加載方法之間,或者你的ImageItem類不能被序列化。對不起,以前從未嘗試序列化BitmapImage,所以我懷疑它。 –
Fendy
2013-03-15 01:44:33
是的,我相信BitmapImage的這些串行化或保存/加載方法是問題的根源,但我不確定如何解決此問題。我在上面的問題中添加了名爲'Setting.cs'的保存/加載方法。 – Matthew 2013-03-15 01:46:53