Lesy
Lesy

Reputation: 3

Datagrid cell color based on cell value

I have a DataGrid with ItemsSource DateTable DTableDay from viewmodel. In DTableDay are cells with null content or with content "1". I want to set green color to cells with content "1"

my xaml looks like this

<DataGrid ItemsSource="{Binding DTableDay}" AutoGenerateColumns="True" > <DataGridCell> <DataGridCell.Style> <Style TargetType="DataGridCell"> <Style.Triggers> <Trigger Property="Content" Value="1"> <Setter Property="Background" Value="Green"/> </Trigger> </Style.Triggers> </Style> </DataGridCell.Style> </DataGridCell> </DataGrid>

But if I run my app it throws an exception with

"Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead."

Can anyone help me please? Thanks

Upvotes: 0

Views: 1579

Answers (2)

M.E.
M.E.

Reputation: 2929

You can define your own DataGridTemplateColumn. In this column you create a new DataTemplate using a simple TextBlock. You bind the TextBlock's Text-Property to the property of object from the DTableDay collection. (In the example below I assume the property name of the binded object is "CellValue".) Then you create a Trigger based on the Text property of the TextBlock.

<DataGrid ItemsSource="{Binding DTableDay}" AutoGenerateColumns="False">
  <DataGrid.Columns>
    <DataGridTemplateColumn>
      <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
          <TextBlock Text="{Binding CellValue}">
            <TextBlock.Style>
              <Style TargetType="TextBlock">
                <Style.Triggers>
                  <Trigger Property="Text" Value="1">
                    <Setter Property="Background" Value="Green"/>
                  </Trigger>
                </Style.Triggers>
              </Style>
            </TextBlock.Style>
          </TextBlock>
        </DataTemplate>
      </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
  </DataGrid.Columns>  
</DataGrid>

Upvotes: 2

user5606561
user5606561

Reputation: 139

A few issues, first "DataGridCell" must be identified with DataGrid (i.e., "DataGrid.DataGridCell") otherwise any other elements in the DataGrid not prefixed with DataGrid. will be interpreted as a item, which means ItemsSource can not be bound again. Secondly, to set the cell style use the DataGrid.CellStyle property.

<DataGrid ItemsSource="{Binding DTableDay}" AutoGenerateColumns="True" >
    <DataGrid.CellStyle>
        <Style TargetType="{x:Type DataGridCell}">
                <!-- your style -->
        </Style>
    </DataGrid.CellStyle>
 <DataGrid />

Upvotes: 0

Related Questions