【问题标题】:Storing colors in ApplicationDataContainer in a Windows Store app在 Windows 应用商店应用中的 ApplicationDataContainer 中存储颜色
【发布时间】:2014-07-02 15:38:00
【问题描述】:

我正在使用以下代码存储我的 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 错误

【问题讨论】:

  • 我建议将字节数组序列化,而不是按原样存储。您可能应该选择"AARRGGBB"。然后,当你想读入它时,只需反序列化它。

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


【解决方案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);
    }

【讨论】:

    猜你喜欢
    • 2014-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多