在Windows应用商店应用中存储ApplicationDataContainer中的颜色

时间:2014-05-14 14:08:41

标签: c# xaml colors windows-runtime windows-store-apps

我正在使用以下代码存储我的Windows应用商店应用的设置

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");
    }
}

但是,当我尝试以这种方式存储Windows.UI.Color的实例时

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

我收到错误。

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

我也尝试将其存储为字节数组:

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");
    }
}

如果我这样做,我会在应用程序运行时遇到System.OutOfMemoryException错误,在同一行

1 个答案:

答案 0 :(得分:1)

例外情况说:不支持此类型的数据。

Color.ToString()允许序列化数据。在应用值之前,您需要转换回颜色:

    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);
    }