简体   繁体   中英

How can I highlight DataGrid's ColumnHeader and RowHeader, when a cell is Selected?

I microsof Excel, when a cell or a group of cells are selected, colums' headers and the rows' headers will be highlighted. How can I implement a similar feature in a wpd DataGrid?

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

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

Check my example:

XAML code:

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

Code-behind:

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 in styleSelected if you want vertical line between columns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM