How to save/load an ObservableCollection of custom class type in WP7

只愿长相守 提交于 2019-12-11 04:20:24

问题


I have created a custom class, named BrowserItem that I am using in my application, that contains a lot of values. I am using this class in an ObservableCollection to store a collection of items. For some reason, although this implementation works while my application is running, I cannot properly get these values to persist when the application closes and then reopens. I am not sure how to properly save and then reload the ObservableCollection of type BrowserItem.

BrowserItem.cs

[DataContract]
public class BrowserItem

{
    [DataMember]
    public FullWebBrowser Browser
    {
        get;
        set;
    }
    [DataMember]
    public string Url
    {
        get;
        set;
    }
    [DataMember]
    public BitmapImage ImageUri
    {
        get;
        set;
    }
    [DataMember]
    public string Title
    {
        get;
        set;
    }
    [DataMember]
    public string Notification
    {
        get;
        set;
    }
    [DataMember]
    public bool DisplayNotification
    {
        get
        {
            return !string.IsNullOrEmpty(this.Notification);
        }
    }
    [DataMember]
    public string Message
    {
        get;
        set;
    }
    [DataMember]
    public string GroupTag
    {
        get;
        set;
    }
    [DataMember]
    //for translation purposes (bound to HubTile Title on MainPage) 
    public string TileName
    {
        get;
        set;
    }
}

Setting.cs (my class that saves and loads from IsolatedStorage)

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;
    }
}

Settings.cs (where the ObservableCollection is initialized)

public static Setting<ObservableCollection<BrowserItem>> BrowserList = new Setting<ObservableCollection<BrowserItem>>("Browsers", new ObservableCollection<BrowserItem>());
    public static Setting<string> InitialUri = new Setting<string>("InitialUri", "http://www.bing.com");

In the above class, InitialUri works fine when new values are saved and then used later, but I believe the issue with the ObservableCollection is its type being BrowserItem. I do not know how to make it so BrowserItem will be able to be used in the ObservableCollection to save and retrieve items that are added to the ObservableCollection. An example of adding an item is below

TabsPage.xaml.cs

void addNew_Click(object sender, EventArgs e)
    {
        BitmapImage newTileImage = new BitmapImage();

        var newItem = new BrowserItem() { Browser = new FullWebBrowser(), Url = "http://www.bing.com", ImageUri = newTileImage, Title = "new", /*Notification = "",*/ Message = "new browser", GroupTag = "TileGroup", TileName = "new" };

        newItem.Browser.InitialUri = Settings.InitialUri.Value;
        Settings.BrowserList.Value.Add(newItem);
    }

Items in the ObservableCollection can be used while the application is active, but not once the application is activated once closed?


回答1:


I had same kind of requirement in my earlier project

Create a class to save and read data from the ObservableCollection

public class SerializeHelper
    {

        public static void SaveData<T>(string fileName, T dataToSave)
        {
            using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                try
                {

                    if (store.FileExists(fileName))
                    {
                        store.DeleteFile(fileName);
                    }

                    using (IsolatedStorageFileStream stream = store.OpenFile(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write))
                    {
                        var serializer = new DataContractSerializer(typeof(T));
                        serializer.WriteObject(stream, dataToSave);
                    }
                }
                catch (Exception e)
                {
                    //MessageBox.Show(e.Message);
                    return;
                }

            }
        }

        public static T ReadData<T>(string fileName)
        {
            using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
            {

                if (store.FileExists(fileName))
                {
                    using (IsolatedStorageFileStream stream = store.OpenFile(fileName, FileMode.OpenOrCreate, FileAccess.Read))
                    {

                        try
                        {
                            var serializer = new DataContractSerializer(typeof(T));
                            return (T)serializer.ReadObject(stream);

                        }
                        catch (Exception)
                        {
                            return default(T);
                        }
                    }
                }
                return default(T);
            }
        }

    }

Saving Data in ISO Store

public ObservableCollection<CustomClass> AllEvents = new public ObservableCollection<CustomClass>();

//AllEvents.Add(customclassref1);
//AllEvents.Add(customclassref2);
//AllEvents.Add(customclassref3);
SerializeHelper.SaveData<ObservableCollection<CustomClass>>("AllEvents", AllEvents);

Retrieving Data from ISO store

AllEvents = (ObservableCollection<CustomClass>)SerializeHelper.ReadData<ObservableCollection<CustomClass>>("AllEvents");


来源:https://stackoverflow.com/questions/12576725/how-to-save-load-an-observablecollection-of-custom-class-type-in-wp7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!