Does anyone know how to convert a string that represents a color into a SolidColorBrush
in WPF?
For e.g:
string colorRed = "Red";
SolidColorBrush fromStringToColor = new SolidColorBrush(colorRed);
That's sort of what I'm trying to accomplish. Any ideas?
Thanks in advance.
You have to convert the string to a System.Windows.Media.Color, which you can do using the static ColorConverter.ConvertFromString method:
string colorRed = "Red";
Color c = (Color)ColorConverter.ConvertFromString(colorRed);
SolidColorBrush fromStringToColor = new SolidColorBrush(c);
private SolidColorBrush GetColorFromString(string color)
{
if (color.StartsWith("#"))
{
if (color.Length == 9)
return new SolidColorBrush(
Color.FromArgb(
Convert.ToByte(color.Substring(1, 2), 16),
Convert.ToByte(color.Substring(3, 2), 16),
Convert.ToByte(color.Substring(5, 2), 16),
Convert.ToByte(color.Substring(7, 2), 16)
)
);
else
if (color.Length == 7)
return new SolidColorBrush(
Color.FromArgb(
0xff,
Convert.ToByte(color.Substring(1, 2), 16),
Convert.ToByte(color.Substring(3, 2), 16),
Convert.ToByte(color.Substring(5, 2), 16)
)
);
}
else
{
Type colorType = (typeof(System.Windows.Media.Colors));
if (colorType.GetProperty(color) != null)
{
object o = colorType.InvokeMember(color,
System.Reflection.BindingFlags.GetProperty, null, null, null); if (o != null)
{
return new SolidColorBrush((Color)o);
}
}
}
return new SolidColorBrush(Colors.Transparent);
}
SolidColorBrush c1 = GetColorFromString("Red");
SolidColorBrush c2 = GetColorFromString("#ffff0000");
SolidColorBrush c3 = GetColorFromString("#ff0000");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With