Ond*_*cek 5 wpf binding datagrid background colors
我有一个名为Color的DataGrid.
<DataGridTextColumn Header="Color" Binding="{Binding MyColor.Percentage}"/>
Run Code Online (Sandbox Code Playgroud)
DataGrid的ItemSource是一个MyColor内部属性的对象.
public class MyColor
{
Color Background { get; set; }
int Percentage { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
设置ItemSource时,列的自动填充值为Percentage.现在我想将此列中每个单元格的背景设置为与MyColor.Color属性对应的颜色.有没有办法使用绑定?就像是
Background="{Binding MyColor.Color}"
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
此外,您必须更改您的MyColor类以具有Background类型的属性Brush,而不是Color.或者您可以使用转换器转换Color为SolidColorBrush.