Silverlight – Get Color from Hex
What if you want to get a Color from its hexa value (#FFBBCC88) ?
Unfortunately Silverlight do not have the ColorTranslator class which allows you to do ColorTranslator.FromHtml("#FF1133") in ASP.NET.
What we have is the Color.FromArgb() method which takes 4 parameters (alpha, red, blue and green channels as bytes).
So here is a small method you could write:
public static SolidColorBrush GetColorFromHexa(string hexaColor) { return new SolidColorBrush( Color.FromArgb( Convert.ToByte(hexaColor.Substring(1, 2), 16), Convert.ToByte(hexaColor.Substring(3, 2), 16), Convert.ToByte(hexaColor.Substring(5, 2), 16), Convert.ToByte(hexaColor.Substring(7, 2), 16) ) ); }
Let’s say I want to set the main Canvas Background (LayoutRoot) from a TextBox (txtColorHexa):
LayoutRoot.Background = GetColorFromHexa(txtColorHexa.Text);
Now add the following Extension method:
public static SolidColorBrush ToSolidColorBrush(this string hexaColor) { return GetColorFromHexa(hexaColor); }
And you get this nice syntax:
LayoutRoot.Background = txtColorHexa.Text.ToSolidColorBrush();