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:
Change WPF Datagrid Row Color
How do I programatically change datagrid row color in WPF?
Programmatically assigning a color to a row in DataGrid
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With