I am using IsolatedStorageSettings.ApplicationSettings for my application. All code associated with Isolated storage occurs in my Application_Launching, Application_Activated, Application_Closing, and Application_Deactivated methods as follows:
public IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
private void Application_Launching(object sender, LaunchingEventArgs e)
{
if (settings.Contains("myObjList"))
{
App.ObjList = (ObservableCollection<myObj>)settings["myObjList"];
}
else
{
settings.Add("myObjList", App.ObjList);
}
}
private void Application_Activated(object sender, ActivatedEventArgs e)
{
if (settings.Contains("myObjList"))
{
App.ObjList = (ObservableCollection<myObj>)settings["myObjList"];
}
else
{
settings.Add("myObjList", App.ObjList);
}
}
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
settings["myObjList"] = App.ObjList;
settings.Save();
}
private void Application_Closing(object sender, ClosingEventArgs e)
{
settings["myObjList"] = App.ObjList;
settings.Save();
}
All of this is occurring in the App.xaml.cs file that is created by default with every new application.
I have tried exiting the application using the back button as well as by using the windows button. Leaving the emulator running, I tried reopening the application using the back button, and navigating to the application list and opening.
The issue I am having is that on load or activation the settings.Contains["myObjList"] is returning false and proceeding to add the key to settings all over again.
Does anyone see why my settings key (and value) is not persisting?
I see some issues:
The IsolatedStorageSettings doc explicitly says not to call Save() because it's not thread safe (scroll down to the platform notes for WP) and may raise an exception (and cause your settings not to be saved).
It seems not to be the case here, but using the string "myObjList" all around is pretty dangerous as it's easy to mispell. I would put it inside a constant and rule out any typing error
In my experience IsolatedStorageSettings is not very robust on the current WP7 version. You better create a class and serialize it into an IsolatedStorage file. Anyways going on with your app you will probably have more things to save and you will have cleaner code that way.
Is your class myObj Serializable? From experience if it's not then no error will be thrown it simply isn't added to IsolatedStorage.
You can use the DataContract and DataMember attributes in your class to enable this as follows.
[DataContract]
public class myObj
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string Id { get; set; }
[DataMember]
public string Phone { get; set; }
来源:https://stackoverflow.com/questions/4330991/why-is-isolated-storage-not-persisting-in-my-wp7-application