开发者

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>


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();
    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜