Question

I'm storing settings for my Windows Store app using the following code

Windows.Storage.ApplicationDataContainer _settings = 
    Windows.Storage.ApplicationData.Current.LocalSettings;

private int _FontSize;
public int FontSize
{
    get
    {
        if (_settings.Values["FontSize"] == null)
            _settings.Values["FontSize"] = 10; // default value 

        _FontSize = (int)_settings.Values["FontSize"];
        return _FontSize;
    }
    set
    {
        _FontSize = value;
        _settings.Values["FontSize"] = _FontSize;
        NotifyPropertyChanged("FontSize");
    }
}

However, when I try and store instances of Windows.UI.Color in this way

if (_settings.Values["BColor"] == null)
    _settings.Values["BColor"] = Windows.UI.Color.FromArgb(255, 220, 220, 220);

I get an error.

WinRT information: 
Error trying to serialize the value to be written to the application data store

I've also tried storing it as a byte array:

private Windows.UI.Color _BColor;
public Windows.UI.Color BColor
{
    get
    {
        if (_settings.Values["BColor"] == null)
            _settings.Values["BColor"] = new byte[255, 220, 220, 220];

        var b = _settings.Values["BColor"] as byte[];
        _BColor = Windows.UI.Color.FromArgb(b[0], b[1], b[2], b[3]);
        return _BColor;
    }
    set
    {
        _BColor = value;
        _settings.Values["BColor"] = new byte[_BColor.A, _BColor.R, _BColor.G, _BColor.B];
        NotifyPropertyChanged("BColor");
    }
}

If I do this I get a System.OutOfMemoryException error when the app runs, on the same line

Était-ce utile?

La solution

The exception says: Data of this type is not supported.

Color.ToString() allows the data to be serialized. You'll need to covert back to a color before applying the value:

    private Color GetColorFromString(string colorHex)
    {
        var a = Convert.ToByte(colorHex.Substring(1, 2),16);
        var r = Convert.ToByte(colorHex.Substring(3, 2),16);
        var g = Convert.ToByte(colorHex.Substring(5, 2),16);
        var b = Convert.ToByte(colorHex.Substring(7, 2),16);
        return Color.FromArgb(a, r, g, b);
    }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top