Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StackPanel.ActualHeight is always zero

Tags:

c#

wpf

stackpanel

I create a StackPanel in run-time and I want to measure the Height of the StackPanel like this:

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

but ActualHeight is alwasy zero. How can I measure the Height Of the StackPanel?

like image 727
mohammad Avatar asked Jun 05 '26 15:06

mohammad


1 Answers

In case you want to measure size without loading content on UI, you have to call Measure and Arrange on containing panel to replicate GUI scenario.

Be notified that how's WPF layout system works, panel first calls Measure() where panel tells its children how much space is available, and each child tells its parent how much space it wants. and then Arrange() is called where each control arranges its content or children based on the available space.

I would suggest to read more about it here - WPF Layout System.


That being said this is how you do it manually:

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();
like image 71
Rohit Vats Avatar answered Jun 07 '26 13:06

Rohit Vats