Reputation: 3071
I have a label in xaml
<Label Content="This is a test"
Foreground="{Binding Path=TextColor, Converter={StaticResource ResourceKey=colorConverter}}" />
in my view model I have the property
public string TextColor
{
get{ return "00FFFF"; }
}
and for my color converter I have the class
public class ColorConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string color = (string)value;
if (!color.Substring(0, 1).Equals("#"))
{ color = color.Insert(0, "#"); }
Color result = (Color)System.Windows.Media.ColorConverter.ConvertFromString(color);
return result;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
Color c = (Color)value;
return string.Format("#{0}{1}{2}", c.R.ToString("x2"), c.G.ToString("x2"), c.B.ToString("x2"));
}
#endregion
}
The color of the text is blac instead of the blue green it is supposed to be. when I step through it, the Convert method appears to return the correct color. I'm not sure where else to look to figure this out.
Upvotes: 0
Views: 60
Reputation: 17402
This will actually work if you just update the converter to return the "formatted" string, instead of trying to cast it to a Color
object.
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string color = (string)value;
if (!color.Substring(0, 1).Equals("#"))
{
color = color.Insert(0, "#");
}
return color ;
}
Though as suggested, there should be no point of having a converter just to add a '#'. This could be done using StringFormat as well (within the binding).. Or just do the conversion inside the property if you really need it.
Upvotes: 1