Reputation:
I have this line and it works but how can i return a custum color string for example "#2228D4"
return (Boolean)value ? new SolidColorBrush(Colors.Red) : new SolidColorBrush(Colors.Yellow);
It's a Windows Phone 8 Application, so I can't use WPF's ColorConverter
.
Upvotes: 2
Views: 3281
Reputation: 600
You can make use of the below method to Convert ColorString(hex code) to Color object.
public Color ConvertStringToColor(String hex)
{
//remove the # at the front
hex = hex.Replace("#", "");
byte a = 255;
byte r = 255;
byte g = 255;
byte b = 255;
int start = 0;
//handle ARGB strings (8 characters long)
if (hex.Length == 8)
{
a = byte.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.HexNumber);
start = 2;
}
//convert RGB characters to bytes
r = byte.Parse(hex.Substring(start, 2), System.Globalization.NumberStyles.HexNumber);
g = byte.Parse(hex.Substring(start + 2, 2), System.Globalization.NumberStyles.HexNumber);
b = byte.Parse(hex.Substring(start + 4, 2), System.Globalization.NumberStyles.HexNumber);
return Color.FromArgb(a, r, g, b);
}
And you can return brush using the below code
(Boolean)value ? new SolidColorBrush(ConvertStringToColor("FFFF0000")) : new SolidColorBrush(ConvertStringToColor("FF00FF00"));
Upvotes: 4
Reputation: 3256
As you're on phone you don't have access to BrushConverter. Do it by breaking the hex down and assigning it to each component instead:
var color = new Color() {R = 0x22, G = 0x28, B = 0xD4};
var brush = new SolidColorBrush(color);
Obviously, keep a reference to brush rather than recreating it over and over :)
Upvotes: 0