Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

All, I am relatively new to WPF. I have searched around for the answer to this, but all I have found is how to do colorise rows at run-time not columns; for example the following questions:

  1. Change WPF Datagrid Row Color

  2. How do I programatically change datagrid row color in WPF?

  3. Programmatically assigning a color to a row in DataGrid

  4. Change DataGrid cell colour based on values

et al.

I have seen the CellStyle property on the MSDN DataGrid pages but its use is not obvious to me at all despite searches around this as well.

how to change the background colour of an entire column at runtime?

Thanks for your time.

like image 607
MoonKnight Avatar asked Mar 26 '13 17:03

MoonKnight


Video Answer


2 Answers

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.

like image 196
Matan Shahar Avatar answered Oct 05 '22 23:10

Matan Shahar


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.

like image 35
dotNET Avatar answered Oct 05 '22 23:10

dotNET