Siento ser tan tarde a la fiesta! Me encontré con un problema similar, en WinRT. No estoy seguro de si está usando WPF o WinRT, pero difieren en algunos aspectos (algunos mejores que otros). Espero que esto ayudará a la gente a través del tablero, lo que en la situación en que están.
Siempre se puede usar el código de la clase convertidor I creado para reutilizar y hacer en su C# de código subyacente, o donde quiera que usarlo, para ser honesta:
I hizo con la intención de que un 6 dígitos (RGB), o un valor Hex 8 dígitos (ARGB) se podrían utilizar de cualquier manera.
así que creé una clase de convertidor:
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();
}
}
Añadido en mi App.xaml:
<ResourceDictionary>
...
<converters:StringToSolidColorBrushConverter x:Key="StringToSolidColorBrushConverter" />
...
</ResourceDictionary>
y lo utilizó en mi Ver Xaml:
<Grid>
<Rectangle Fill="{Binding RectangleColour,
Converter={StaticResource StringToSolidColorBrushConverter}}"
Height="20" Width="20" />
</Grid>
trabaja un ¡encanto!
Nota al pie ... Desafortunadamente, WinRT no ha conseguido el System.Windows.Media.BrushConverter
que H. B. sugerido; así que necesitaba de otro modo, de lo contrario habría hecho una propiedad que devuelve un VM SolidColorBrush
(o similar) de la propiedad RectangleColour
cadena.
¿Es posible hacerlo de una sola línea? – heltonbiker
@heltonbiker: Sí, ¿por qué no? –
Bueno, al final estoy usando 'Fill = (SolidColorBrush) new BrushConverter(). ConvertFromString (" # 76EB7E ");', que encontré en otra respuesta SO y es bastante idéntica a esta respuesta! ¡Bonito! – heltonbiker