Welsh King
Welsh King

Reputation: 3238

StackPanel within a StackPanel alignment not right

I have a StackPanel that contains child StackPanels (added in code behind).

Parent StackPanel

    <StackPanel Name="spDaysWeather"  Grid.Column="0" Grid.ColumnSpan="2" HorizontalAlignment="Stretch" Grid.Row="3" Orientation="Horizontal">



    </StackPanel>

Child StackPanels

for (int i=1;i<WeatherList.Count;i++)
        {
            StackPanel StackPanelDay = new StackPanel { Orientation =Orientation.Vertical, VerticalAlignment = VerticalAlignment.Stretch, HorizontalAlignment= HorizontalAlignment.Stretch};
            Label day = new Label { Content = WeatherList[i].weatherdate.DayOfWeek, FontSize = 10 };
            System.Windows.Controls.Image imgweather = new System.Windows.Controls.Image { Source = ReturnCultureImage(String.Format("weather_{0}", WeatherList[i].condition.ToLower().Replace(" ", "_"))), Width = 75, Height = 75};

            StackPanelDay.Children.Add(day);
            StackPanelDay.Children.Add(imgweather);
            spDaysWeather.Children.Add(StackPanelDay);

        }

When I run the application I get the following display

page view

The Black box is the parent StackPanel. The red squares are the child StackPanels that I am adding dynamically.

How can I get the children to center vertically, and also resize should the application window change size.

Should I use a StackPanel or is there another Panel that would be better suited ?

Many thanks

Upvotes: 2

Views: 8734

Answers (1)

Jehof
Jehof

Reputation: 35554

Put your parent StackPanel in a Grid and change the HorizontalAlignment of the StackPanel to Center.

XAML:

<Grid Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="3">
  <StackPanel Name="spDaysWeather" HorizontalAlignment="Center" Orientation="Horizontal">
  </StackPanel>
</Grid>

It should also work if you set only the HorizontalAlignment of the StackPanel to Center.

XAML:

<StackPanel Name="spDaysWeather" 
            Grid.Column="0"
            Grid.ColumnSpan="2"
            HorizontalAlignment="Center"
            Grid.Row="3" 
            Orientation="Horizontal"/>

Upvotes: 3

Related Questions