How can I highlight a DataGrid ColumnHeader and RowHeader when a cell is selected?

I microsof Excel, when a cell or group of cells is selected, column headers and row headers are highlighted. How to implement a similar function in wpd DataGrid?

I think I need to handle the DataGrid.SelectionChanged event, but I have no idea how I can proceed. any help is appreciated.

+4
source share
1 answer

I think the easiest way to do this is to use the SelectedCellsChanged event.

Check out my example:

XAML Code:

  <DataGrid Name="myData" AutoGenerateColumns="True" SelectionMode="Extended" SelectionUnit="Cell" SelectedCellsChanged="myData_SelectedCellsChanged" /> 

Code for:

 private void myData_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e) { foreach (var item in myData.Columns) { item.HeaderStyle = null; } if (myData.SelectedCells != null && myData.SelectedCells.Count != 0) { Style styleSelected = new Style(); styleSelected.Setters.Add(new Setter(Border.BackgroundProperty, new SolidColorBrush(Colors.Orange))); foreach (var item in myData.SelectedCells) { item.Column.HeaderStyle = styleSelected; } } } 

You can also set Border.BorderBrushProperty and Border.BorderThicknessProperty to styleSelected if you want a vertical line between the columns.

+1
source

All Articles