如何获得stackpanel的实际当前高度?

时间:2010-09-10 10:21:53

标签: wpf xaml panel stackpanel

喂,

我想在WPF中创建一个自定义堆栈面板,它会根据面板高度自动调整其子节点的大小。但是面板高度是动态的,因为它延伸到他的父母。当我想获得高度(我尝试了所有可能性,请参阅代码)时,它始终为0或未定义,但在构建解决方案中它绝对不是0。 这是代码:

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

2 个答案:

答案 0 :(得分:3)

这可能与 实际查询this.ActualHeight时有关。在调用AddChild()时,高度确实可能仍为0,因为the measure pass and the arrange pass可能尚未通过。影响孩子的度量和布局的一切都应该在MeasureOverrideArrangeOverride

中完成

您应该看看如何编写自定义面板。那里有很多关于这个主题的资源。我个人认为this是一本很好且简单的教程。

答案 1 :(得分:0)

ActualHeight是正确的属性,但在您正在阅读它时,尚未计算高度。

点击此链接,了解构建自定义布局面板的推荐方法:http://www.wpftutorial.net/CustomLayoutPanel.html