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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With