Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save an enumeration into ApplicationData.Current.LocalSettings

Turns out that WinRT's ability to save settings throws an exception when you try to store an enumeration value. MSDN says on the page "Accessing app data with the Windows Runtime" that only "Runtime Data Types" are supported.

So, how do you save an enum?

like image 238
Jerry Nixon Avatar asked Oct 05 '12 15:10

Jerry Nixon


1 Answers

That's a really strange behavior. But easy to solve.

First you need some type of parse routine like this:

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

Note: the default value of an ENUM is always its 0 value member.

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're just transforming it to a string.

like image 107
Jerry Nixon Avatar answered Nov 15 '22 10:11

Jerry Nixon