How can i change the background color of text when the cell is selected in datagrid in WPF
How to change background color of selected text inside datagrid cell in WPF
2.8k views Asked by Naveen Kumar At
2
There are 2 answers
0
On
You Can achieve this using Triggers Like this.
<DataGrid.CellStyle>
<Style TargetType="DataGridCell" >
<Style.Triggers>
<Trigger Property="IsEditing" Value="True">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="DataGridCell">
<TextBox Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content.Text, Mode=TwoWay, UpdateSourceTrigger=Default}"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Padding="0" BorderThickness="0" Background="SeaGreen"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Trigger>
<Style.Triggers>
</Style>
</DataGrid.CellStyle>
Here is a full example on this in case you have a TextBox on those DataGridRows:
All the magic happens here:
A simple Person class for this:
And the code behind for testing purposes:
Case 2
You define your DataTemplate as non editable and still want to select the cell:
You change you style to :
Why is this working like this?
Because the SelectionUnit property of the DataGrid is set to Cell, only a single cell is affected. If the SelectionUnit is set to FullRow, then the background color is applied to all cells in the selected row.