Converting Hexadecimals to Colors in code for Silverlight
Unfortunately this type conversion is not readily accessible when working in code. In code there are two options built-in, the FromArgb method and system-defined colors.
ellipse.Fill = new SolidColorBrush (Color.FromArgb(255, 29, 177, 0));
//using a system-defined color
ellipse.Fill = new SolidColorBrush (Colors.Green);
As a fan of defining colors using hexadecimals, like myself, you may find switching to bytes in code bothersome. Happily we can do something about this.
The code sample below converts an unsigned integer, which can be written in hexadecimal format, into a Color structure. Not only are we avoiding string parsing by using the uint type and bitwise operators, we’re also taking advantage of extension methods in C#. This allows us to extend the uint type and reuse this method anywhere in code that has a reference to our ColorExtensions class.
public static class ColorExtensions
public static Color ToColor(this uint argb)
return Color.FromArgb((byte)((argb & -16777216) >> 0x18),
(byte)((argb & 0xff0000) >> 0x10),
(byte)((argb & 0xff00) >> 8),
(byte)(argb & 0xff));
//sample usage within a different class
ellipse.Fill = new SolidColorBrush (0xFF1DB100.ToColor());
And that’s it! You can now define color values using hexadecimal in your XAML and C# code.
(If you’re new to Silverlight and want to learn more about the SolidColorBrush class referenced and Brushes in general, check out the Brushes in Silverlight documentation.)