Search code examples
c#wpfxamlentity-framework-coredatagrid

Change datagrid cell or row color based on its content


I am normally using triggers for this approach as follows. However, in this case I have a dynamic datagrid (from database) where I can't set the triggers for static columns.

<DataGridTemplateColumn Width="*" Header="Id">
    <DataGridTemplateColumn.CellStyle>
        <Style TargetType="{x:Type DataGridCell}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Content, RelativeSource={RelativeSource Self}}" Value="ERROR">
                    <Setter Property="Background" Value="Red"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGridTemplateColumn.CellStyle>
</DataGridTemplateColumn>

How to set the same trigger for a dynamic content? I am setting the datagrid content as,

private void setEFdatagrid() 
{
    using (FBaseContext context = new FBaseContext())
    {
        var listItems = context.TLoggers.ToList();

        loggerItems = new ObservableCollection<TLogger>(listItems);

        datagridLogger.ItemsSource = loggerItems;
    }               
}

Solution

  • Your approach is correct, but you are missing a step inside your DataTrigger binding.

    DataGridCell.Content it's not the value of the bounded property itself (I suppose TLogger.ID), but the ContentControl that holds that value (for example a Textblock). So, if you want to perform this binding correctly you have two ways: binding DataTrigger to the property, or binding it to Content.Text (in case of text cell)

    I think that the simplest solution is the second one, so this code will work:

    <DataGridTemplateColumn Width="*" Header="Id">
    <DataGridTemplateColumn.CellStyle>
        <Style TargetType="{x:Type DataGridCell}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Content.Text, RelativeSource={RelativeSource Self}}" Value="ERROR">
                    <Setter Property="Background" Value="Red"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGridTemplateColumn.CellStyle>