wpf - 我怎样才能得到堆栈面板的实际当前高度?

标签 wpf xaml panel stackpanel

你好,

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

XAML:

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

代码隐藏:

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

最佳答案

这可能与您实际查询 this.ActualHeight时间有关。在调用 AddChild() 时,高度可能仍为 0,因为 the measure pass and the arrange pass可能还没有通过。所有影响 child 尺寸和布局的事情都应该在MeasureOverride中完成和 ArrangeOverride

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

关于wpf - 我怎样才能得到堆栈面板的实际当前高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3683833/

相关文章:

wpf - 如何使用触发器检查复选框?

wpf - WPF/Silverlight/XAML 中的强类型数据绑定(bind)?

javascript - 改变mozilla插件工具提示框的样式

python - 如何在 wx.Panel 背景上做 dregradê?

GridBagLayout + GridLayout 的 Java 问题

c# - WPF Storyboard : DoubleAnimation Works On Opacity But Not TranslateTransform?

c# - WPF TabControl 如何在鼠标向上而不是鼠标向下时更改 Tab?

c# - Wpf 置于最前面

c# - WPF中如何设置外边框、居中边框和内边框?

wpf - 如何使基于 XAML 的 UI 开发变得可以忍受?