Sorry to be so late to the party! I came across a similar issue, in WinRT. I'm not sure whether you're using WPF or WinRT, but they do differ in some ways (some better than others). Hopefully this will help people across the board, whichever situation they're in.
You could always use the code from the converter class I created to re-use and do in your C# code-behind, or wherever you're using it, to be honest:
I made it with the intention that a 6-digit (RGB), or an 8-digit (ARGB) Hex value could be used either way.
So I created a converter class:
public class StringToSolidColorBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
var hexString = (value as string).Replace("#", "");
if (string.IsNullOrWhiteSpace(hexString)) throw new FormatException();
if (hexString.Length != 6 || hexString.Length != 8) throw new FormatException();
try
{
var a = hexString.Length == 8 ? hexString.Substring(0, 2) : "255";
var r = hexString.Length == 8 ? hexString.Substring(2, 2) : hexString.Substring(0, 2);
var g = hexString.Length == 8 ? hexString.Substring(4, 2) : hexString.Substring(2, 2);
var b = hexString.Length == 8 ? hexString.Substring(6, 2) : hexString.Substring(4, 2);
return new SolidColorBrush(ColorHelper.FromArgb(
byte.Parse(a, System.Globalization.NumberStyles.HexNumber),
byte.Parse(r, System.Globalization.NumberStyles.HexNumber),
byte.Parse(g, System.Globalization.NumberStyles.HexNumber),
byte.Parse(b, System.Globalization.NumberStyles.HexNumber)));
}
catch
{
throw new FormatException();
}
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
Added it into my App.xaml:
<ResourceDictionary>
...
<converters:StringToSolidColorBrushConverter x:Key="StringToSolidColorBrushConverter" />
...
</ResourceDictionary>
And used it in my View's Xaml:
<Grid>
<Rectangle Fill="{Binding RectangleColour,
Converter={StaticResource StringToSolidColorBrushConverter}}"
Height="20" Width="20" />
</Grid>
Works a charm!
Side note...
Unfortunately, WinRT hasn't got the System.Windows.Media.BrushConverter
that H.B. suggested; so I needed another way, otherwise I would have made a VM property that returned a SolidColorBrush
(or similar) from the RectangleColour
string property.