While Fredrik's answer provides a refactored approach with an additional method that could potentially be reused in other parts of the code, I preferred to combine its methods with one method.There may also be a slight increase in performance since it can complete the search as soon as it finds the header , and you donβt need to continue searching for all the children in the visualization tree (this is in most cases insignificant).
private DataGridColumnHeader GetHeader(DataGridColumn column, DependencyObject reference) { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(reference); i++) { DependencyObject child = VisualTreeHelper.GetChild(reference, i); DataGridColumnHeader colHeader = child as DataGridColumnHeader; if ((colHeader != null) && (colHeader.Column == column)) { return colHeader; } colHeader = GetHeader(column, child); if (colHeader != null) { return colHeader; } } return null; }
And it is used like this:
DataGridColumnHeader colHeader = GetHeader(column, myDataGrid); if (colHeader == null) { }
source share