找到DataGridColumn的根元素

我递归地使用
LogicalTreeHelper.GetParent()
方法来查找各种其他WPF元素的根元素。几乎所有东西都可以正常工作,但是对于DataGridColumn,例如
DataGridTextColumn
,它会失败。 我发现
DataGridColumn
不是逻辑树和视觉树的一部分。我能以某种方式找到它所属的
DataGrid
(然后从网格中获取根)吗? 阅读MSDN文档我找不到合适的解决方案。谢谢。 我的代码找到逻辑根:
private DependencyObject FindLogicalRoot(DependencyObject obj)
{
  if (obj == null)
     return null;
   else
   {
       var parent = LogicalTreeHelper.GetParent(obj);
       return parent != null ? FindLogicalRoot(parent) : obj;
   }
 }
    
已邀请:
DataGridColumn具有此属性,但它是私有的,因此您必须使用反射来获取它。要么在VisualTree中进行一些搜索,要么将每个DataGrid的Columns与要查找的Column进行比较
public DataGrid GetDataGridParent(DataGridColumn column)
{
    PropertyInfo propertyInfo = column.GetType().GetProperty("DataGridOwner", BindingFlags.Instance | BindingFlags.NonPublic);
    return propertyInfo.GetValue(column, null) as DataGrid;
}
    
var grid = ((Telerik.Windows.Controls.GridView.GridViewCellBase)
           ((sender as FrameworkElement).Parent)).Column.DataControl;
    

要回复问题请先登录注册