Converting hex string into Color (Windows Phone)

By | 2013-09-18

In Windows Phone (Silverlight) there is no System.Drawing.ColorTranslator.FromHtml(“#cccccc”); or similar that can help you convert a hex string into a color object. To do this you’ll have to parse the string yourself.

So is a simple method that will do so, it supports both “argb” and “rgb” with or without “#” in front of it. Meaning: The string “#aabbcc” or “#ffaabbcc” or “aabbcc” or “ffaabbcc” will be converted to a Color object.

ValueConverter for Xaml

Since I will be using this in Xaml databinding I created a ValueConverter for it:

Note that because I will be using a fairly low number of different colors I have added a (thread safe) “_brushCache” dictionary. This will speed up reuse of same color codes as its not necessary to parse the string and recreate Color and SolidBrush objects every time the color is used.

Usage

Add resource

To use this converter in databinding first add it as a resource.

  1. Recompile project. After any change to codebehind that affects Xaml (such as creating a new “ColorHexStringToBrushConverter” class) you need to recompile once. If not Visual Studio Xaml editor will complain that the object doesn’t exist.

  2. Inside the “<PhoneApplicationPage …>” or “<UserControl …>” tag you need to append a namespace reference, for example if converter is in namespace “YourProject.Utils”:

  1. Inside “<UserControl.Resources>” (add it before first “<Grid>”  if it doesn’t exist already) add:

Databind with Converter

Then in your page / user control where you databind simply add “Converter={StaticResource ColorHexStringToBrushConverter }” to your databinding.

For example:

As String extension method

You could add it as a string extension method:

And then use it as:

When deserializing

Warning: The following section is untested. Added it just for fun.

You can create an object type of it that can be used more directly.

 

 

 

4 thoughts on “Converting hex string into Color (Windows Phone)

  1. Chris

    This line:

    return Color.FromArgb(a, r, b, g);

    Should be

    return Color.FromArgb(a, r, g, b);

    You have the a, r, g, b parameters in the wrong order

    Reply
  2. Dieter

    Thanks for the solution, I faced the same problem today.
    One remark: you have to compose your color in this way -> return Color.FromArgb(a, r, g, b);

    Reply

Leave a Reply