Search code examples
wpfxamlpanelstackpanel

How can i get the real current height of a stackpanel?


Hallo,

i want to make a custom stackpanel in WPF, which shall automatically resizes his childs to a certain size depending on the panels height. But the panels height is dynamic because it stretches to his parent. When i want to get the height (i tried all possibilities, see code), it is always 0 or not defined, although in the build solution it is definitely not 0. Here's the code:

XAML:

<my:AutoSizeButtonStackPanel HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>

Code-Behind:

public class AutoSizeButtonStackPanel : StackPanel
{
    public void AddChild(Button newButton)
    {
        double getPanelHeight;
        getPanelHeight = this.ActualHeight; //is 0
        getPanelHeight = this.ViewportHeight; //is 0
        getPanelHeight = this.Height; //is n. def.
        getPanelHeight = this.DesiredSize.Height; //is 0
        getPanelHeight = this.RenderSize.Height; //is 0

        newButton.Height = getPanelHeight / 2;

        this.Children.Add(newButton);
    }
}

Solution

  • This might have to do with when you actually query this.ActualHeight. At the time AddChild() is called the height really might still be 0 because the measure pass and the arrange pass might not have been through yet. Everything that affects the measure and layout of your children should be done in MeasureOverride and ArrangeOverride

    You should have a look at how to write custom Panels. There are tons of ressources on this topic out there. I personally think that this is a good and simple enough tutorial.