tags:

views:

20

answers:

1

Hello All

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??

+1  A: 

Hi!

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!

Almund
That works like a charm.. this is what i am exactly looking for.. yes simple is king.. :)
prem