开发者

Find datagrid column name when a cell is clicked in datagrid

开发者 https://www.devze.com 2023-01-20 20:32 出处:网络
I wanted to find the datagrid column header when a cell is clicked.. i used the following code private void grid1_Pr开发者_开发技巧eviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)

I wanted to find the datagrid column header when a cell is clicked.. i used the following code

private void grid1_Pr开发者_开发技巧eviewMouseLeftButtonUp(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!

0

精彩评论

暂无评论...
验证码 换一张
取 消