I have a WPF DataGrid with autogenerated columns and i needed a very specific style in the cells as you can see in the next image.
To do this i have created CellStyles depending on the column index to get the desired colors composition, like this for headers.
datagrid.Columns[colIndex].HeaderStyle = new Style(typeof(DataGridColumnHeader));
datagrid.Columns[colIndex].HeaderStyle.Setters.Add(new Setter(Control.BackgroundProperty, (SolidColorBrush)new BrushConverter().ConvertFrom(colors[colorIndex])));
datagrid.Columns[colIndex].HeaderStyle.Setters.Add(new Setter(Control.BorderBrushProperty, (SolidColorBrush)new BrushConverter().ConvertFrom(colors[colorIndex])));
datagrid.Columns[colIndex].HeaderStyle.Setters.Add(new Setter(Control.FontWeightProperty, FontWeights.Bold));
datagrid.Columns[colIndex].HeaderStyle.Setters.Add(new Setter(Control.FontSizeProperty, 18.0));
like this for cells that require a specific color
datagrid.Columns[colIndex].CellStyle = new Style(typeof(DataGridCell));
datagrid.Columns[colIndex].CellStyle.Setters.Add(new Setter(Control.BackgroundProperty, (SolidColorBrush)new BrushConverter().ConvertFrom(colors[colorIndex])));
datagrid.Columns[colIndex].CellStyle.Setters.Add(new Setter(Control.BorderBrushProperty, (SolidColorBrush)new BrushConverter().ConvertFrom(colors[colorIndex])));
datagrid.Columns[colIndex].CellStyle.Setters.Add(new Setter(TextBlock.FontWeightProperty, FontWeights.Bold));
datagrid.Columns[colIndex].CellStyle.Setters.Add(new Setter(TextBlock.FontSizeProperty, 18.0));
datagrid.Columns[colIndex].IsReadOnly = true;
Everything is ok to this point, but, when i click on a row, the cells which style has been defined with "CellStyle = new Style" becomes all white, background and foreground, and i don't know how what i have to change to get the row data to be visible.
Thanks!
CodePudding user response:
Define custom colours for the HighlightBrushKey
and HighlightTextBrushKey
brushes:
<DataGrid ...>
<DataGrid.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent"/>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Black"/>
</DataGrid.Resources>
...
</DataGrid>