c# - 将 System.Windows.Media.Color 绑定(bind)到 TextBlock.Foreground?

标签 c# .net wpf xaml colors

当我这样做时,我得到:

"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."

有人知道怎么做吗?

为什么 WPF 不能自动转换它,因为我使用的是 WPF 颜色,而不是 System.Drawing.Color。

编辑:

Xaml 代码:

<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>

最佳答案

Brush 类型的默认 TypeConverter,不支持 Color(即使是 WPF 版本)。它只支持与字符串之间的转换。

您必须创建一个自定义的 IValueConverter,它接受一个 Color 并返回一个 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();
    }

}

关于c# - 将 System.Windows.Media.Color 绑定(bind)到 TextBlock.Foreground?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5423687/

相关文章:

c# - 从强类型 Razor View 使用 Html.BeginForm 传递值

c# - 找不到可安装的 ISAM

c# - 将流转换为字节串

c# - BusyIndi​​cator 允许两次触发 RelayCommand

c# - 在 C# 中,如何避免引号中断

c# - 如何在二进制图像中找到最大的 'blob'

.net - 在执行Process.Start()时,是否需要将其包装在using中?

c++ - 您的计算机中缺少 api-ms-win-core-winrt-string-l1-1-0.dll

wpf - 是否保证在调用 OnStartup() 时所有 WPF 绑定(bind)都将起作用?

wpf - Windows 7 触摸屏 "Shrug"