StackPanel.ActualHeight始终为零

时间:2014-03-09 12:33:00

标签: c# wpf stackpanel

我在运行时创建了一个StackPanel,我想像这样衡量Height的{​​{1}}:

StackPanel

但是StackPanel panel = new StackPanel(); panel.Children.Add(new Button() { Width = 75, Height = 25 }); Title = panel.ActualHeight.ToString(); 是零。如何衡量ActualHeight的{​​{1}}?

4 个答案:

答案 0 :(得分:2)

如果您想在不在UI上加载内容的情况下衡量尺寸,则必须在包含面板上调用MeasureArrange 来复制GUI场景。

通知WPF布局系统是如何工作的,面板首先调用Measure(),其中面板告诉孩子有多少可用空间,每个孩子告诉其父母他们想要多少空间。然后调用Arrange(),每个控件根据可用空间排列其内容或子项。

我建议在这里阅读更多相关信息 - WPF Layout System


说到这就是你手动操作的方式:

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

答案 1 :(得分:0)

我不完全确定你要做什么,但这段代码有效:

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

通常,在布局和渲染之前,您将无法访问堆栈面板的大小。这发生在面板的Loaded事件之前,因此您可以处理该事件并处理它。

答案 2 :(得分:0)

尝试在ActualHeight事件中获取Loaded

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

答案 3 :(得分:0)

试试这个:

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