I wanted to find the datagrid column header when a cell is 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 a direct parent for the datagrid cell so its not able to find it. is there anyother way out??
The original source being clicked isn't really connected to the so called item container (see the DataGrid.ItemContainerGenerator) so trying to work yourself up the hiearchy, although a nice idea won't get you to far.
For a quite silly simple solution you could use the knowledge of it being only one cell being clicked and thus using that clicked cell to retrieve the column, as 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 perhaps ain´t the prettiest of solutions but simple is king.
Hope it helps!
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