18
votes

I'm trying to change the colour of Text in the selected row in a WPF datagrid. By default it changes the text colour white is there a way to change this using styles / triggers etc?

Thanks in advance!

2

2 Answers

29
votes

Try this

<Style x:Key="DataGridCellStyle" TargetType="{x:Type DataGridCell}" >
    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Foreground" Value="Green"/>
        </Trigger>
    </Style.Triggers>
</Style>

Then you can use it in the columns that you see fit like

<DataGrid ...>
    <DataGrid.Columns>
        <DataGridTextColumn CellStyle="{StaticResource DataGridCellStyle}" .../>

If you want it to apply to all columns you can change the x:key of the Style to

<Style x:Key="{x:Type DataGridCell}" TargetType="{x:Type DataGridCell}" >
2
votes

If you want to completely remove the Foreground color changes (say, if your DataGrid has different colors for different rows), you can do this:

    <Style TargetType="{x:Type DataGridCell}" BasedOn="{StaticResource {x:Type DataGridCell}}">
        <Style.Triggers>
            <Trigger Property="IsSelected" Value="True">
                <Setter Property="Foreground" Value="{Binding RelativeSource={RelativeSource Self}, Path=Foreground}" />
            </Trigger>
        </Style.Triggers>
    </Style>

If you want to give this style a name, like in the previous answer, add x:Key.