Search code examples
c#wpfxamlwpfdatagriddatagridtextcolumn

How to set DataGridTextColumn text color?


I'm trying to change the color of a DataGridTextColumn.

Here's what I'm doing:

<DataGridTextColumn 
    Header="Status" 
    Binding="{Binding IsActive, 
               Converter= {StaticResource BoolToStatusConverter}}"
    Foreground="{Binding Path=IsActive,
               Converter={StaticResource BoolToColorConverter}}"/>

Text is set properly, but the color won't change, and I'm getting following error:

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or 
FrameworkContentElement for target element. BindingExpression:Path=IsActive; 
DataItem=null; target element is 'DataGridTextColumn' (HashCode=40349079); target 
property is 'Foreground' (type 'Brush')

What should I do for this to work?


Solution

  • You need to specify a Style with a DataTrigger for the column's CellStyle. e.g.

    <Page.Resources>
        <Style TargetType="DataGridCell" x:Key="ActiveCellStyle">
            <Setter Property="Foreground" Value="Blue"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsActive}" Value="{x:Null}">
                    <Setter Property="Foreground" Value="Green"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding IsActive}" Value="True">
                    <Setter Property="Foreground" Value="Red"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
        <Converters:BoolToTextConverter 
            x:Key="BoolToStatusConverter" 
            TargetCondition="True" 
            IsMatchValue="It's active" 
            IsNotMatchValue="It's dead" />
    </Page.Resources>
    <Grid>
        <DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn 
                    Header="Status" 
                    Binding="{Binding IsActive, 
                        Converter={StaticResource BoolToStatusConverter}}" 
                    CellStyle="{StaticResource ActiveCellStyle}"/>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>