Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Color Code to SolidColor Conversion

0.00/5 (No votes)
10 Jan 2012 1  
I think there might be a couple of typos in the original code. This works, though...public SolidColorBrush GetColor(string ColorCode){ return (SolidColorBrush)XamlReader.Load( <SolidColorBrush xmlns=http://schemas. + microsoft.com/winfx/2006/xaml/presentation...
I think there might be a couple of typos in the original code. This works, though...

C#
public SolidColorBrush GetColor(string ColorCode)
{
    return (SolidColorBrush)XamlReader.Load(
        "<SolidColorBrush xmlns=\"http://schemas." +
        "microsoft.com/winfx/2006/xaml/presentation\" Color=\"" + 
        ColorCode + "\" />");
}


Alternatively you could do something like this rather than use the XamlReader...

C#
public static SolidColorBrush GetColor(string s)
{
    //this method assumes "#00000000" or "00000000" format and DOES NOT VALIDATE - add anti-splode code here!
    int hashOffset = s.Substring(0, 1) == "#" ? 1 : 0; //accounts for "#FF000000" format
    byte a = Convert.ToByte(s.Substring(0 + hashOffset, 2), 16);
    byte r = Convert.ToByte(s.Substring(2 + hashOffset, 2), 16);
    byte g = Convert.ToByte(s.Substring(4 + hashOffset, 2), 16);
    byte b = Convert.ToByte(s.Substring(6 + hashOffset, 2), 16);
    return new SolidColorBrush(Color.FromArgb(a, r, g, b));
}


Laurent Duveau has a nice implementation with an extension method here[^].

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here