Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding System.Windows.Media.Color to TextBlock.Foreground?

When I do this I get:

"Cannot create default converter to perform 'one-way' conversions between types 'System.Windows.Media.Color' and 'System.Windows.Media.Brush'. Consider using Converter property of Binding."

Anyone knows how to do this?

Why can't WPF convert this automatically as I am using WPF colors, not System.Drawing.Color.

EDIT:

Xaml code:

<GridViewColumn Width="120" Header="Info">
    <GridViewColumn.CellTemplate>
        <DataTemplate>
            <TextBlock HorizontalAlignment="Center" Text="{Binding Info, Mode=OneWay}" Foreground="{Binding MessageColor, Mode=OneWay}"/>
        </DataTemplate>
    </GridViewColumn.CellTemplate>
</GridViewColumn>
like image 818
Joan Venge Avatar asked Mar 24 '11 18:03

Joan Venge


1 Answers

The default TypeConverter for the Brush type, does not support Color (even the WPF version). It only supports converting to/from strings.

You would have to create a custom IValueConverter that takes a Color and returns a SolidColorBrush.

public class ColorToBrushConverter : IValueConverter {

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
        if (!(value is Color))
            throw new InvalidOperationException("Value must be a Color");
        return new SolidColorBrush((Color)value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
        throw new NotImplementedException();
    }

}
like image 196
CodeNaked Avatar answered Sep 29 '22 04:09

CodeNaked