(1)方式一:
Color color1 = (Color)System.Windows.Media.ColorConverter.ConvertFromString("#E0E0E0");
(2)方式二:
Color color2 = ConvertToColor("#E0E0E0");
public static System.Windows.Media.Color ConvertToColor(string value)
{
int r = 0, g = 0, b = 0;
if (value.StartsWith("#"))
{
int v = Convert.ToInt32(value.Substring(1), 16);
r = (v >> 16) & 255; g = (v >> 8) & 255; b = v & 255;
} return System.Windows.Media.Color.FromRgb(Convert.ToByte(r), Convert.ToByte(g), Convert.ToByte(b));
}
记住:如果是将RGB(128,24,34)转换为十六进制,可以分别将数字转换为十六进制:
public string toHex(int digit)
{
string hexDigit = digit.ToString("X");
if (hexDigit.Length == 1)
{
hexDigit = "0" + hexDigit;
}
return hexDigit;
}
然后拼接得到十六进制:
string colorCode = "#" +toHex(Color.R) +toHex(Color.G) +toHex(Color.B);
(3)方法三
private static Color CreateColorFromString(string s)
{
if (string.Compare(s, "None") == )
{
return Colors.Transparent;
}
s = s.Replace("#", "");
byte result = ;
byte num2 = ;
byte num3 = ;
byte num4 = ;
byte.TryParse(s.Substring(, ), NumberStyles.HexNumber, (IFormatProvider)null, out result);
byte.TryParse(s.Substring(, ), NumberStyles.HexNumber, (IFormatProvider)null, out num2);
byte.TryParse(s.Substring(, ), NumberStyles.HexNumber, (IFormatProvider)null, out num3);
byte.TryParse(s.Substring(, ), NumberStyles.HexNumber, (IFormatProvider)null, out num4);
return System.Windows.Media.Color.FromArgb(result, num2, num3, num4);
}