How to save enumeration in ApplicationData.Current.LocalSettings

It turns out that WinRT's ability to save settings throws an exception when you try to save an enumeration value. MSDN says on the "Access Application Data Using Windows Runtime" page as "Runtime Data Types" .

So how do you keep the listing?

+4
source share
2 answers

This is really weird behavior. But easy to solve.

First you need some type of parsing procedure, for example:

T ParseEnum<T>(object value) { if (value == null) return default(T); return (T)Enum.Parse(typeof(T), value.ToString()); } 

Note: the default value for ENUM is always its value.

Then you can interact with it like this:

 var _Settings = ApplicationData.Current.LocalSettings.Values; // write _Settings["Color"] = MyColors.Red.ToString() // read return ParseEnum<MyColors>(_Settings["Color"]); 

Basically, we just convert it to a string.

+4
source

Another way to achieve this is by using a basic enumeration type to serialize a value.

 public void Write<T>(string key, T value) { var settings = ApplicationData.Current.LocalSettings; if (typeof(T).GetTypeInfo().IsEnum) { settings.Values[key] = Convert.ChangeType(value, Enum.GetUnderlyingType(typeof(T))); return; } settings.Values[key] = value; } public bool TryRead<T>(string key, out T value) { var settings = ApplicationData.Current.LocalSettings; object tmpValue; if (settings.Values.TryGetValue(key, out tmpValue)) { if (tmpValue == null) { value = default(T); return true; } if (typeof(T).GetTypeInfo().IsEnum) { value = (T)Enum.ToObject(typeof(T), tmpValue); return true; } if (tmpValue is T) { value = (T) tmpValue; return true; } } value = default(T); return false; } 

Usage example

 // write Write("Color", MyColors); // read MyColor value; TryRead<MyColor>("Color", out value) 
+1
source

Source: https://habr.com/ru/post/1438022/


All Articles