Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF SolidColorBrush dilemma

Tags:

wpf

brush

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.

like image 211
CODES_ONLY Avatar asked Jun 01 '09 21:06

CODES_ONLY


2 Answers

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);
like image 114
Guy Starbuck Avatar answered Sep 20 '22 17:09

Guy Starbuck


        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");
like image 33
Dmitry Avatar answered Sep 22 '22 17:09

Dmitry