Silverlight: Convert Hex RGB to Color

Spent a few minutes looking up the answer to this one:

I have an RGB color in traditional HTML Hex notation, like #1d5d8f. How do I create a SolidColorBrush in this color?

I’m sure I must be missing something easier, but here’s the C# code to do it:

byte r = System.Convert.ToByte("1d", 16);
byte g = System.Convert.ToByte("5d", 16);
byte b = System.Convert.ToByte("8f", 16);
Color s = Color.FromRgb(r, g, b);
Brush b = new SolidColorBrush(s);

1 Response to “Silverlight: Convert Hex RGB to Color”


  1. 1 Carl June 12, 2008 at 1:24 pm

    …and, in Silverlight 2.0 b2:

    public Color getColorFromHexString(string s)
    {
    byte a = System.Convert.ToByte(s.Substring(0, 2), 16);
    byte r = System.Convert.ToByte(s.Substring(2, 2), 16);
    byte g = System.Convert.ToByte(s.Substring(4, 2), 16);
    byte b = System.Convert.ToByte(s.Substring(6, 2), 16);
    return Color.FromArgb(a, r, g, b);
    }


Leave a comment




TwitterCounter for @anthonyrstevens
Add to Technorati Favorites

RSS Feed

View Anthony Stevens's profile on LinkedIn