0

How do I convert solid color to color code in c#?

if (t == 2)
{
     x.Foreground = new SolidColorBrush(Colors.Green);
}

I need to get value from color code like #ffeeee instead of color name.

I have tried :

abc.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#ffaacc"));

But I can't use ColorConverter is there is any other way?

mxmissile
  • 11,464
  • 3
  • 53
  • 79
alisa
  • 13
  • 5
  • 1
    Does this answer your question? [How do I get the color from a hexadecimal color code using .NET?](https://stackoverflow.com/questions/2109756/how-do-i-get-the-color-from-a-hexadecimal-color-code-using-net) – Pepijn Bakker Jan 10 '23 at 15:38

2 Answers2

2

You can use ColorConverter, but it retuns a System.Drawing.Color. The problem is that the SolidColorBrush constructor takes a Windows.UI.Color.

There is a very simple way to convert the color from System.Drawing to Windows.UI:

public static Windows.UI.Color GetColorFromHex(string hexaColor)
{
    //get the color as System.Drawing.Color
    var clr = (System.Drawing.Color)new ColorConverter().ConvertFromString(hexaColor);

    //convert it to Windows.UI.Color
    return Windows.UI.Color.FromArgb(clr.A, clr.R, clr.G, clr.B);
} 
FrozenAssassine
  • 1,392
  • 1
  • 7
  • 16
-1
Color _color = System.Drawing.ColorTranslator.FromHtml("#ff0008");

abc.Foreground = _color;

You can try this, it worked with me.

mxmissile
  • 11,464
  • 3
  • 53
  • 79
  • 1
    System.Drawing.ColorTranslator is part of the System.Drawing namespace which is Windows Forms and not present in WPF project, I don't know if this is the case – Baptistin Jan 10 '23 at 15:53