While working in Silverlight I needed a way to convert from hex string representations of colors to a brush (SolidColorBrush in this case). Below is the extension method I wrote including a way to convert from a named color.
public static class ColorFromHex {
public static SolidColorBrush ToSolidColorBrush(this string hexString) {
SolidColorBrush brush = null;
try {
if (hexString.Length == 7) {
//return brush with opacity of 1
brush = new SolidColorBrush(
Color.FromArgb(
Convert.ToByte("FF", 16),
Convert.ToByte(hexString.Substring(1, 2), 16),
Convert.ToByte(hexString.Substring(3, 2), 16),
Convert.ToByte(hexString.Substring(5, 2), 16))
);
}
else {
brush = new SolidColorBrush(
Color.FromArgb(
Convert.ToByte(hexString.Substring(1, 2), 16),
Convert.ToByte(hexString.Substring(3, 2), 16),
Convert.ToByte(hexString.Substring(5, 2), 16),
Convert.ToByte(hexString.Substring(7, 2), 16))
);
}
}
catch (Exception) {
//try to convert from named color
try {
Colors colors = null;
PropertyInfo prop = typeof(Colors).GetProperty(hexString);
if (prop != null)
brush = new SolidColorBrush((Color)prop.GetValue(colors, null));
}
catch (Exception) { }
}
return brush;
}
}
In practice it’s as easy as this:
SolidColorBrush scb = myHexStringFromConfigFileOrWhatever.ToSolidColorBrush();