Find datagrid column name when cell is clicked in datagrid

I wanted to find the column header of the datagrid when the cell was clicked. I used the following code

private void grid1_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e) { DependencyObject dep = (DependencyObject)e.OriginalSource; while ((dep != null) && !(dep is DataGridColumnHeader)) { dep = VisualTreeHelper.GetParent(dep); } if (dep == null) return; if (dep is DataGridColumnHeader) { DataGridColumnHeader columnHeader = dep as DataGridColumnHeader; if (columnHeader.ToString() == "Adv Comments") { MessageBox.Show(columnHeader.Column.Header.ToString()); } } if (dep is DataGridCell) { DataGridCell cell = dep as DataGridCell; } } 

But the column header is not the direct parent for the datagrid cell, so it cannot find it. is there any other way out

+4
source share
1 answer

The original source source is not connected to a container with the so-called element container (see DataGrid.ItemContainerGenerator), therefore, trying to figure out hiearchy, although a good idea will not lead you far.

For pretty dumb simple solutions, you could use the knowledge that it only clicked one , and thus using this cell with a click to get a column like this:

 private void DataGrid_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e) { // First check so that weΒ΄ve only got one clicked cell if(myGrid.SelectedCells.Count != 1) return; // Then fetch the column header string selectedColumnHeader = (string)myGrid.SelectedCells[0].Column.Header; } 

This may not be the most beautiful of solutions, but the simplest is the king.

Hope this helps!

+7
source

All Articles