Is there a way to store instances of own classes in the ApplicationSettings of a Windows Store app?

∥☆過路亽.° 提交于 2019-12-10 19:17:35

问题


In a Windows Store app I can only store WinRT types in the ApplicationSettings, according to the documentation. For roamed settings that should be held together I can use ApplicationDataCompositeValue. Trying to store an instance of an own class or struct results in an Exception with the message " WinRT information: Error trying to serialize the value to be written to the application data store. Additional Information: Data of this type is not supported". The term "trying to serialize" indicates that there must be some way so serialize a type for the application data API.

Does anyone know how I could achieve that?

I tried DataContract serialization but it did not work.


回答1:


I think custom/own types are not supported.

See http://msdn.microsoft.com/en-us/library/windows/apps/hh464917.aspx: "The Windows Runtime data types are supported for app settings."

But you can serialize your objects to XML and save as string... (see code below)

public static string Serialize(object obj)
{
    using (var sw = new StringWriter()) 
    {
        var serializer = new XmlSerializer(obj.GetType());
        serializer.Serialize(sw, obj);
        return sw.ToString();
    }
}

public static T Deserialize<T>(string xml)
{
    using (var sw = new StringReader(xml))
    {
        var serializer = new XmlSerializer(typeof(T));
        return (T)serializer.Deserialize(sw);
    }
}

https://github.com/MyToolkit/MyToolkit/blob/master/src/MyToolkit/Serialization/XmlSerialization.cs

Check out this class too:

https://github.com/MyToolkit/MyToolkit/wiki/XmlSerialization

Disclaimer: The above links are from my project



来源:https://stackoverflow.com/questions/12553485/is-there-a-way-to-store-instances-of-own-classes-in-the-applicationsettings-of-a

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