سؤال

I am using the LogicalTreeHelper.GetParent() method recursively to find the root elements of various other WPF elements. This works fine with almost everything, but it fails for the DataGridColumn such as DataGridTextColumn. I found out that DataGridColumn is not part of the Logical Tree nor the Visual Tree. Can I somehow find the DataGrid it belongs to (and then get the root from the grid)?

Reading the MSDN documentation I could not find a suitable solution. Thank you.

My code to find the logical root:

private DependencyObject FindLogicalRoot(DependencyObject obj)
{
  if (obj == null)
     return null;
   else
   {
       var parent = LogicalTreeHelper.GetParent(obj);
       return parent != null ? FindLogicalRoot(parent) : obj;
   }
 }
هل كانت مفيدة؟

المحلول

DataGridColumn has this property but it's private so you'll have to use reflection to get it. Either that or do some searching in the VisualTree and compare Columns for each DataGrid to the Column you want to find

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;
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top