如何从“ANY”十进制值获取SolidColorbrush / Brush

时间:2015-10-24 18:32:43

标签: c# wpf

我有一个转换器,用于将十进制颜色值转换为SolidColorBrush,这些值存储在数据库中。

我分两步进行转换。

  1. Transalte decimal to Hexadecimal
  2. 将十六进制转换为SolidColorBrush
  3. 以下是代码:

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        try
        {
            string HexVal = string.Format("#{0}", (Int32.Parse(value.ToString())).ToString("X"));
            return new SolidColorBrush((Color)ColorConverter.ConvertFromString(HexVal));
        }
        catch (Exception ex )
        {
           . . . .
        }
    }
    

    现在我的问题是一些非常好的价值观,如7897995,255和其他。但是当尝试像black(0)这样的东西时会引发异常。像

    这样的东西

    System.FormatException:符号(标记)无效。    在MS.Internal.Parsers.ParseColor(String color,IFormatProvider formatProvider,ITypeDescriptorContext context)    在System.Windows.Media.ColorConverter.ConvertFromString(String value)

    我试着:

    (SolidColorBrush)(new BrushConverter().ConvertFrom(HexVal));
    

    (Brush)(new BrushConverter().ConvertFrom(HexVal))
    

    现在我有两个问题:

    1. 如果#FFFF00是有效颜色,为什么不能将其转换为SolidColorbrush?
    2. 有更好的方法来执行此转换吗?

1 个答案:

答案 0 :(得分:1)

您应该直接将值转换为int,而不是从int获取RGB字节,并从这些字节创建Color值:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    var decimalValue = (decimal)value;
    var intValue = (int)decimalValue;
    var bytes = BitConverter.GetBytes(intValue);
    var color = Color.FromRgb(bytes[2], bytes[1], bytes[0]);
    return new SolidColorBrush(color);
}

仅供参考,您的方法中的问题是字符串格式"#{0}",例如,为黑色创建#0而不是#000000