Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF DataGrid cell background using binding

I have a DataGrid with column named Color.

<DataGridTextColumn Header="Color" Binding="{Binding MyColor.Percentage}"/>

The ItemSource of DataGrid is some object with MyColor property inside.

public class MyColor
{
    Color Background { get; set; }
    int Percentage { get; set; }
}

When ItemSource is set column auto-fills with values of Percentage. Now I'd like to set background of each cell in this column to color corresponding to MyColor.Color property. Is there a way to do it using binding? Something like

Background="{Binding MyColor.Color}"

Color property is in html format #XXXXXXXX (is it called html format?).

like image 491
Ondrej Janacek Avatar asked Oct 21 '11 14:10

Ondrej Janacek


1 Answers

You can set it via CellStyle:

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

Also you have to change your MyColor class to have a Background property with type Brush, not Color. Or you can use a converter to convert Color into SolidColorBrush.

like image 52
Snowbear Avatar answered Sep 30 '22 15:09

Snowbear