问题
I am learning programming in windows 8 with c#. I have worked through many tutorials (such as http://msdn.microsoft.com/en-us/library/windows/apps/hh986968.aspx) in the process and I am attempting to create a simple app showing data storage. All of the examples I have been able to find store only simple strings in roaming storage. Is there a way to store more complex data there?
example: a List of a basic class Person with a name and age. I attempted to do it as:
Saving the data:
roamingSettings.Values["peopleList"] = people;
Loading the Data:
people = (List)roamingSettings.Values["peopleList"];
WinRT information: Error trying to serialize the value to be written to the application data store. when saving the data I get the error "Data of this type is not supported"
So, maybe all you can save is string values -- but I have not seen that specified anywhere either.
回答1:
Yes, you can save your values to raoming data as a collection. The solution for your problem is
ApplicationDataCompositeValue class
See http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.applicationdatacompositevalue.aspx for more information
As you mentioned, You are developing in C# , following is the code for your problem I imagined, you have a Person class with two members
class person
{
int PersonID;
string PersonName
}
Now, to read and write values for this class, here is the code
First in the constructor of your Window class, under the InitializeComponent();, create an object of roaming settings
Windows.Storage.ApplicationDataContainer roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings;
To Write to a composition, use the following code
void write (Person Peopleobj)
{
Windows.Storage.ApplicationDataCompositeValue composite = new Windows.Storage.ApplicationDataCompositeValue();
composite["PersonID"] = Peopleobj.PersonID;
composite["PersonName"] = Peopleobj.PersonName;
roamingSettings.Values["classperson"] = composite;
}
To Read a Person object, use the following code
void DisplayOutput()
{
ApplicationDataCompositeValue composite = (ApplicationDataCompositeValue)roamingSettings.Values["classperson"];
if (composite == null)
{
// "Composite Setting: <empty>";
}
else
{
Peopleobj.PersonID = composite["PersonID"] ;
Peopleobj.PersonName = composite["PersonName"];
}
}
来源:https://stackoverflow.com/questions/13473136/windows-8-app-roaming-storage-with-custom-class