5

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;
   }
 }
mbuchetics
  • 1,370
  • 1
  • 17
  • 34
  • Hi ... I can see why DataGridColumn is not part of the visual or logical tree. The DataGrid.Columns property is a regular property, just like TextBlock.Text or any other property. The DataGrid uses your column definition too generate columns, however the definition itself is not added to the visual tree. Can I ask why you are wanting to navigate from DataGridColumn to its parent? – ColinE Dec 23 '10 at 11:30
  • I am writing a MarkupExtension where I need to find the type of the root element. – mbuchetics Dec 23 '10 at 12:30
  • So what you want to do is to find the Parent DataGrid from a DataGridColumn, correct? – Fredrik Hedblad Dec 23 '10 at 14:19

2 Answers2

6

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;
}
Fredrik Hedblad
  • 83,499
  • 23
  • 264
  • 266
  • If the DataGridOwner property is not set, you can not get it. Then the function returns null. Moreover, an explicit query not necessary, because if you have a column, even so the DataGridOwner's turn: column.DataGridOwner – peter70 May 20 '14 at 12:37
0
var grid = ((Telerik.Windows.Controls.GridView.GridViewCellBase)
           ((sender as FrameworkElement).Parent)).Column.DataControl;
McGarnagle
  • 101,349
  • 31
  • 229
  • 260
Malcolm Swaine
  • 109
  • 1
  • 3