Search code examples
wpfheaderheightexpander

Get the Height of the WPF Expander Header


I need to get the Height of the WPF Expander.Header, not the whole Expander just the Height of the Header.

There is no property to get it because the Expander.Header + Expander.Content is the Expander.Height.

What would you do to get the Expander.Header Height ?


Solution

  • If your expander isn't templated, that's a Visual tree:

    Expander { Border { DockPanel { ToggleButton, ContentPresenter {...} } } }
    

    All you need is to get that ToggleButton. It's easy using VisualTreeHelper:

    var border = VisualTreeHelper.GetChild(expander, 0);
    var dockpanel = VisualTreeHelper.GetChild(border, 0);
    var togglebutton = VisualTreeHelper.GetChild(dockpanel, /*0*/); // it may be not 0th, so please enumerate all children using VisualTreeHelper.GetChildrenCount(dockpanel) and find that ToggleButton
    return togglebutton.ActualHeight;
    

    Edit

    Also, I'd like to accent on using ActualHeight, not Height, because Height is not double.IsNaN (in XAML, auto) only if set explicitly in code or XAML