Frage

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?

War es hilfreich?

Lösung

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

Andere Tipps

Try get the ActualHeight in Loaded event:

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

I'm not entirely sure what you're trying to do, but this code works:

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

In general, you won't be able to access the size of a stackpanel until it is laid out and rendered. This happens prior to the panel's Loaded event, so you could handle that event and deal with it then.

Try this:

panel.UpdateLayout(); //this line may not be necessary.
Rect bounds = VisualTreeHelper.GetDescendantBounds(panel);
var panelHeight = bounds.Height;
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top