5
votes

When I set a WPF DataGrid's ColumnHeaderHeight to Auto (double.NaN), how do I get the actual rendered height of the column header?

I cannot seem to find the property in the DataGrid class.

2

2 Answers

5
votes

You could get hold of it by searching through the visual tree for the DataGridColumnHeadersPresenter and reading its ActualHeight property.

    var headersPresenter = FindVisualChild<DataGridColumnHeadersPresenter>(dataGrid);
    double actualHeight = headersPresenter.ActualHeight;

Here's the FindVisualChild method. It could be implemented as an extension method as well.

public static T FindVisualChild<T>(DependencyObject current) where T : DependencyObject
{
    if (current == null) return null;
    int childrenCount = VisualTreeHelper.GetChildrenCount(current);
    for (int i = 0; i < childrenCount ; i++)
    {
        DependencyObject child = VisualTreeHelper.GetChild(current, i);
        if (child is T) return (T)child;
        T result = FindVisualChild<T>(child);
        if (result != null) return result;
    }
    return null;
}
0
votes

When I remember correctly, the property is an attached property - meaning the real value should be found on a DataGridColumn.

There is a separate class for the DataGridColumnHeader with the same name - see: http://msdn.microsoft.com/de-de/library/system.windows.controls.primitives.datagridcolumnheader(v=vs.110).aspx

This class can probably be gained through a single DataGridColumns "Header" property. See: http://msdn.microsoft.com/en-us/library/system.windows.controls.datagridcolumn.header(v=vs.110).aspx

So I would grab the first column of the grid, convert it's Header property to DataGridColumnHeaderand read its actualheight attribute.

Please make sure to guard for the case that the Header attribute or ActualHeight is null - this can happen when the grid is build / refreshing or closing. I dimly remeber that there should be an event which is fired when the grid is rendered completely.