开发者

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.ViewportH开发者_开发技巧eight; //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);
    }
}


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜