question

njsokalski avatar image
0 Votes"
njsokalski asked ·

GridLength.Star Not Working For HorizontalAlignment="Center"

I have a Grid as follows:

<Grid Grid.Row="3" HorizontalAlignment="Center" VerticalAlignment="Center">
<Grid.RowDefinitions><RowDefinition Height=""/><RowDefinition Height=""/></Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width=""/>
<ColumnDefinition Width="
"/>
<ColumnDefinition Width=""/>
<ColumnDefinition Width="
"/>
<ColumnDefinition Width=""/>
<ColumnDefinition Width="
"/>
<ColumnDefinition Width=""/>
<ColumnDefinition Width="
"/>
<ColumnDefinition Width=""/>
<ColumnDefinition Width="
"/>
<ColumnDefinition Width=""/>
<ColumnDefinition Width="
"/>
</Grid.ColumnDefinitions>
<Border Padding="5" BorderBrush="Black" BorderThickness="1,1,0.5,1"><Path HorizontalAlignment="Center" VerticalAlignment="Center" StrokeThickness="0" Fill="Green" Data="M10 20H0L19.5 0L40 20H29V26.5H10Z"/></Border>
<Border Grid.Column="1" Padding="5" BorderBrush="Black" BorderThickness="0.5,1,0.5,0.5"><TextBlock FontFamily="Arial" FontSize="32" Foreground="Black" TextAlignment="Center" OpticalMarginAlignment="TrimSideBearings" TextLineBounds="Tight" Text="2" VerticalAlignment="Center"/></Border>
</Grid>

Note that all ColumnDefinition(s) have Width="*", which I would expect to make all columns the same width. However, this is giving me the following:

7927-gridcenter.png


But if I change the Grid to HorizontalAlignment="Stretch" (instead of Center), I get the following:
7840-gridstretch.png


Is there any way to center the Grid without wrapping it in another element (such as another Grid)? Thanks.

windows-uwp-xaml
gridcenter.png (3.8 KiB)
gridstretch.png (3.5 KiB)
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

danielescipioni avatar image
0 Votes"
danielescipioni answered ·

You defined too many columns, try to put only 2 ColumnDefinitions




· 4 ·
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

That doesn't make any difference, even once I fill in all columns it does the same thing


0 Votes 0 ·

Please try to add a width value for the Grid. If not, the grid will automatically resize the size of the element based on the size. If the value of HorizontalAlignment/VerticalAlignment is Stretch, the element will stretch to fill the available space in the grid cell. Please check this document: Layout panels.


0 Votes 0 ·

That would be great if I knew or calculated the width of all the Children, however, doing this could be very tedious, especially for things such as borders & margins, or if the size of an element changes. Any other ideas?


0 Votes 0 ·

If you don't want to set the width of it, then you might need to warp the grid with some elements.

0 Votes 0 ·