StackPanel.ActualHeight is always zero

本文关键字:zero always is ActualHeight StackPanel | 更新日期: 2023-09-27 17:49:19

我在运行时创建了一个StackPanel,我想像这样测量StackPanelHeight:

StackPanel panel = new StackPanel();
panel.Children.Add(new Button() { Width = 75, Height = 25 });
Title = panel.ActualHeight.ToString();

,但ActualHeight始终为零。如何测量StackPanel中的Height

StackPanel.ActualHeight is always zero

如果你想在UI上不加载内容的情况下测量大小,你必须调用MeasureArrange上包含面板来复制GUI场景。

注意WPF布局系统是如何工作的,panel首先调用Measure(), panel告诉它的子节点有多少空间可用,然后每个子节点告诉它的父节点它想要多少空间。然后调用Arrange(),其中每个控件根据可用空间安排其内容或子控件。

我建议在这里阅读更多关于它的内容- WPF布局系统。


话虽如此,这是你手动操作的方法:

StackPanel panel = new StackPanel();
panel.Children.Add(new Button() { Width = 75, Height = 25 });
panel.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
panel.Arrange(new Rect(0, 0, panel.DesiredSize.Width, panel.DesiredSize.Height));
Title = panel.ActualHeight.ToString();

尝试在Loaded事件中获取ActualHeight:

private void Button_Click(object sender, RoutedEventArgs e)
{
    var panel = new StackPanel();
    var button = new Button();
    button.Width = 75;
    button.Height = 25;
    panel.Children.Add(button);
    panel.Loaded += new RoutedEventHandler(panel_Loaded);
    MainGrid.Children.Add(panel);
}
private void panel_Loaded(object sender, RoutedEventArgs e)
{
    Panel panel = sender as Panel;
    Title = panel.ActualHeight.ToString();
}

我不完全确定您想要做什么,但是这段代码可以工作:

this.SetBinding(Window.TitleProperty, 
                new Binding()
                     {
                         Source = panel,
                         Path = new PropertyPath("ActualHeight")
                     });

一般来说,在布局和呈现之前,您无法访问stackpanel的大小。这发生在面板的Loaded事件之前,所以您可以处理该事件,然后再处理它。

试试这个:

panel.UpdateLayout(); //this line may not be necessary.
Rect bounds = VisualTreeHelper.GetDescendantBounds(panel);
var panelHeight = bounds.Height;