使用绑定的WPF DataGrid单元格背景

使用绑定的WPF DataGrid单元格背景,wpf,binding,datagrid,colors,background,Wpf,Binding,Datagrid,Colors,Background,我有一个DataGrid,列名为Color <DataGridTextColumn Header="Color" Binding="{Binding MyColor.Percentage}"/> 设置ItemSource时,列自动填充百分比的值。现在,我想将此列中每个单元格的背景设置为对应于MyColor.color属性的颜色。有没有一种使用绑定的方法?差不多 Background="{Binding MyColor.Color}" Color属性为html格式#XXXXXXXX

我有一个DataGrid,列名为Color

<DataGridTextColumn Header="Color" Binding="{Binding MyColor.Percentage}"/>
设置ItemSource时,列自动填充
百分比的值。现在,我想将此列中每个单元格的背景设置为对应于
MyColor.color
属性的颜色。有没有一种使用绑定的方法?差不多

Background="{Binding MyColor.Color}"

Color
属性为html格式#XXXXXXXX(是否称为html格式?)

您可以通过
CellStyle
设置它:

<DataGridTextColumn Header="Color" Binding="{Binding MyColor.Percentage}">
    <DataGridTextColumn.CellStyle>
        <Style TargetType="DataGridCell">
            <Setter Property="Background" Value="{Binding MyColor.Background}" />
        </Style>
    </DataGridTextColumn.CellStyle>
</DataGridTextColumn>


您还必须更改
MyColor
类,使其具有类型为
Brush
Background
属性,而不是
Color
。或者您可以使用转换器将
颜色
转换为
SolidColorBrush

好的,我管理了将输入转换为SolidColorBrush,但出现了一个问题。由于应用程序的其余部分,我使用Dispatcher将ItemSource分配给DataGrid,当我将您的XAML代码添加到我的应用程序中时,会弹出错误“必须在与DependencyObject相同的线程上创建DependencySource”
<DataGridTextColumn Header="Color" Binding="{Binding MyColor.Percentage}">
    <DataGridTextColumn.CellStyle>
        <Style TargetType="DataGridCell">
            <Setter Property="Background" Value="{Binding MyColor.Background}" />
        </Style>
    </DataGridTextColumn.CellStyle>
</DataGridTextColumn>