Set color through color code in c#

Jitendra Jadav picture Jitendra Jadav · Jun 18, 2010 · Viewed 64.3k times · Source

I am trying to add color in c# code, with the following color code for example.

ListTreeView.Background = new SolidColorBrush(Colors.White);

This is working..but I want to add this color as color code so I am add as

System.Windows.Media

Could someone give me an example with

System.Drawing

So what I can do the following:

ListTreeView.Background = ColorTranslator.FromHtml("#FFE7EFF2");

This gives me error ; Any Ideas?

Answer

Keith picture Keith · Jun 18, 2010

There isn't an easy way to get the colour with alpha included from a hex string in this way.

I think your answer depends on where you're getting the colour and alpha values from.

The RGB colour alone can be parsed from an HTML hex string:

Color colour = ColorTranslator.FromHtml("#E7EFF2");

If you have a separate alpha value you can then apply this (docs):

Color colour = ColorTranslator.FromHtml("#E7EFF2");
Color transparent = Color.FromArgb(128, colour);

Alternatively you may need to parse the string and split it out to convert the hex pairs into integer values.

PS excuse English spelling, but colour should definitely have a 'u' in it :)