Wpf 在datagrid中单击单元格时查找datagrid列名
我想在单击单元格时找到datagrid列标题。。我使用了以下代码Wpf 在datagrid中单击单元格时查找datagrid列名,wpf,datagrid,Wpf,Datagrid,我想在单击单元格时找到datagrid列标题。。我使用了以下代码 private void grid1_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e) { DependencyObject dep = (DependencyObject)e.OriginalSource; while ((dep != null) && !(dep i
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;
}
}
但是列标题不是datagrid单元格的直接父级,因此无法找到它。还有其他解决方法吗???被点击的原始源并没有真正连接到所谓的项目容器(参见DataGrid.ItemContainerGenerator),所以尝试自己建立层次结构,尽管一个好主意不会让你走得更远 对于一个非常愚蠢的简单解决方案,您可以使用以下知识,即只单击一个单元格,从而使用该单元格检索列,如下所示:
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;
}
这也许不是最漂亮的解决方案,但简单就是王道
希望有帮助 那很有魅力。。这正是我要找的。。是的,简单就是国王……)