Search code examples
c#uwpgriduwp-xamlstackpanel

how to vertically align a child item in centre of its parent height


I have a stack panel which has another stack panel and I would like the second panel to be at the centre of first stack panel.I changed orientation of these panels and vertical alignment nothing works..

Anybody worked on this ? I would like to have your help.

Update:

 <StackPanel Grid.Row="0" Grid.RowSpan="4" Background="White" Visibility="Visible" Orientation="Vertical">

                <StackPanel VerticalAlignment="Center" Grid.Row="0">
                    <ProgressBar Margin="0,15,0,0"
                     IsIndeterminate="True" 
                     IsEnabled="True" Foreground="Black"/>
                    <TextBlock Visibility="Visible" Margin="6,6,6,15" Foreground="Black" FontSize="21" TextWrapping="WrapWholeWords" HorizontalAlignment="Center" Text="Loading..."/>
                </StackPanel>
        </StackPanel>

Solution

  • The problem here is the StackPanel. What stack panel does is that it stacks the items from one side (top, left...) so it's not possible to fully center an item in StackPanel. When items are stacked vertically, the VerticalAlignment property has no effect on items that are direct children of the panel. The same applies for HorizontalAlignment and horizonal stacking.

    You should use Grid or Border to center items (I also removed the Visibility values since Visible is the default state):

    <Grid Grid.Row="0"
          Grid.RowSpan="4"
          Background="White"
          >
        <StackPanel HorizontalAlignment="Center"
                    VerticalAlignment="Center"
                    Grid.Row="0"
                    >
            <ProgressBar Margin="0,15,0,0"
                         IsIndeterminate="True" 
                         IsEnabled="True"
                         Foreground="Black"
                         />
            <TextBlock Margin="6,6,6,15"
                       Foreground="Black"
                       FontSize="21"
                       TextWrapping="WrapWholeWords"
                       HorizontalAlignment="Center"
                       Text="Loading..."
                       />
        </StackPanel>
    </Grid>