Change the Background Color of Entire Column of WPF DataGrid at RunTime Change the Background Color of Entire Column of WPF DataGrid at RunTime wpf wpf

Change the Background Color of Entire Column of WPF DataGrid at RunTime


The only way I got it to work is by setting the columns by myself, (by not using AutoGenerate). So first thing to do is define the columns:

<DataGrid x:Name="Frid" ItemsSource="{Binding Path=.}">        <DataGrid.Columns>            <DataGridTextColumn Header="First Name"                                 Binding="{Binding Path=FirstName}">            </DataGridTextColumn>            <DataGridTextColumn Header="Last Name"                                 Binding="{Binding Path=LastName}">            </DataGridTextColumn>        </DataGrid.Columns>    </DataGrid> 

Then you need to set each column CellStyle and bind the Background to a static resource that you can declare at Window.Resources:

<Window x:Class="WpfApplication1.MainWindow" ...><Window.Resources>    <SolidColorBrush x:Key="clBr" Color="White" /></Window.Resources>...

Columns:

                <DataGridTextColumn Header="First Name"                                     Binding="{Binding Path=FirstName}">                <DataGridTextColumn.CellStyle>                    <Style TargetType="DataGridCell">                        <Setter Property="Background"                                 Value="{StaticResource clBr}" />                    </Style>                </DataGridTextColumn.CellStyle>            </DataGridTextColumn>

then you can just manipulate the static resource by either code or xaml manipulation.

Hope it helps.


A bit old, but here is how you can do this programmatically (for AutoGen columns):

private void dgvMailingList_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e){    e.Column.CellStyle = new Style(typeof(DataGridCell));    e.Column.CellStyle.Setters.Add(new Setter(DataGridCell.BackgroundProperty,  new SolidColorBrush(Colors.LightBlue)));}

The same approach can be applied to non-AutoGen columns too.