Change Background Color of Selected Cells in WPF DataGrid in XAML
By Michael Detras
Changing the background color of selected cells in a WPF DataGrid can easily be done by using styles in XAML.
The following XAML shows the style used for changing the background color of a DataGridCell.
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:system="clr-namespace:System;assembly=mscorlib"
Title="MainWindow" Height="125" Width="200">
<Window.Resources>
<Style TargetType="DataGridCell">
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<StackPanel>
<DataGrid AutoGenerateColumns="False" SelectionUnit="Cell">
<DataGrid.ItemsSource>
<Int32Collection>
<system:Int32>1</system:Int32>
<system:Int32>2</system:Int32>
</Int32Collection>
</DataGrid.ItemsSource>
<DataGrid.Columns>
<DataGridTextColumn Header="Integers" Binding="{Binding Mode=OneWay}"/>
<DataGridTextColumn Header="Some Column"/>
</DataGrid.Columns>
</DataGrid>
</StackPanel>
</Window>
And here is the window screenshot.
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. In the example above, the rightmost (empty) column used in filling the empty space of the DataGrid won't be affected. If we want the background color to be applied to it as well, we need to specify a style for the DataGridRow class, like the one below.
<Style TargetType="DataGridRow">
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>
Related FAQs
The WPF DataGrid is meant for showing a large amount of data. Due to this, it is confusing to see many rows without any alternating row colors.
Change Background Color of Selected Cells in WPF DataGrid in XAML (11360 Views)