views:

42

answers:

2

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);
    }
}
A: 

ActualHeight is the correct property, but at the point where you're reading it, the height is not calculated yet.

Follow this link to find out the recommended way of building a custom layout panel: http://www.wpftutorial.net/CustomLayoutPanel.html

Rob Fonseca-Ensor
I already knew this tutorial, but it's not profound enough and doesn't clear my problem.
SpeziFish
+1  A: 

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.

bitbonk
Thanks, good tutorial (even simple enough for me :-P )Had to put the resize logic in ArrangeOverride, now it works.
SpeziFish