Find the root element of a DataGridColumn

I use the LogicalTreeHelper.GetParent() method recursively to find the root elements of various other WPF elements. This works fine with just about everything, but for a DataGridColumn it fails, like a DataGridTextColumn . I found out that DataGridColumn not part of a logical tree or visual tree. Can I somehow find the DataGrid that it belongs to (and then get the root from the grid)?

While reading the MSDN documentation, I did not find a suitable solution. Thanks.

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; } } 
+4
source share
2 answers

DataGridColumn has this property, but it is private, so you need to use reflection to get it. Either that, or do some search operations in VisualTree and compare the columns for each DataGrid in the column that 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; } 
+5
source
 var grid = ((Telerik.Windows.Controls.GridView.GridViewCellBase) ((sender as FrameworkElement).Parent)).Column.DataControl; 
0
source

Source: https://habr.com/ru/post/1333177/


All Articles