How to get DataGridColumnHeader from DataGridColumn?

My code is as follows:

void mainDataContextObj_CutSelectedColumnEvent(string columnId) { IList<DataGridColumn> columns = dg.Columns; for(int i=2; i<dg.Columns.Count; i++) { DataGridColumnHeader headerObj = dg.Columns[i].Header as DataGridColumnHeader; //This always returns headerObj as null!!! } } 

I need a DataGridColumnHeader from a column. Where am I going wrong? Please, help!

+4
source share
2 answers

The DataGridColumn header object is actually the visible header of this column, regardless of what you set it to. The DataGridColumn is not part of the Visual Tree, so there is no direct access to the DataGridColumnHeader for it (we cannot even be sure that it exists). But you can do something similar to try to access it.

 DataGridColumnHeader headerObj = GetColumnHeaderFromColumn(column); private DataGridColumnHeader GetColumnHeaderFromColumn(DataGridColumn column) { // dataGrid is the name of your DataGrid. In this case Name="dataGrid" List<DataGridColumnHeader> columnHeaders = GetVisualChildCollection<DataGridColumnHeader>(dataGrid); foreach (DataGridColumnHeader columnHeader in columnHeaders) { if (columnHeader.Column == column) { return columnHeader; } } return null; } public List<T> GetVisualChildCollection<T>(object parent) where T : Visual { List<T> visualCollection = new List<T>(); GetVisualChildCollection(parent as DependencyObject, visualCollection); return visualCollection; } private void GetVisualChildCollection<T>(DependencyObject parent, List<T> visualCollection) where T : Visual { int count = VisualTreeHelper.GetChildrenCount(parent); for (int i = 0; i < count; i++) { DependencyObject child = VisualTreeHelper.GetChild(parent, i); if (child is T) { visualCollection.Add(child as T); } else if (child != null) { GetVisualChildCollection(child, visualCollection); } } } 
+13
source

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) { /* Not found */ } 
+4
source

All Articles