Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UWP XAML: How to get an auto-sized Grid with equal column widths

Tags:

xaml

uwp

uwp-xaml

My goal is to have a Grid panel that has two columns of controls (each column will contain a vertical StackPanel), where both columns are the same width but auto-sized based on the controls they contain. So both column widths will be equal to the widest control in either column.

I tried doing something like this:

<Grid HorizontalAlignment="Center">
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="*" />
    <ColumnDefinition Width="*" />
  </Grid.ColumnDefinitions>
  <Button Grid.Column="0" Content="This is a wide button" HorizontalAlignment="Center" />
  <Button Grid.Column="1" Content="Button" HorizontalAlignment="Center" />
</Grid>

The problem here is that the column widths aren't equal. The effect is the same as if I would have specified Width="Auto" for the column definitions. Using a * width only makes the columns equal width if the grid has a HorizontalAlignment of Stretch instead of Center. (Except then the columns aren't auto-sized to the content anymore.)

Am I missing something? Is there a way to get equal-sized column widths based on the content in the grid cells? In a UWP app (so things like UniformGrid aren't available)?

like image 668
Jazzman Avatar asked Dec 30 '25 04:12

Jazzman


2 Answers

Thats because you have set HorizontalAlignment to "Center" , Grid wont occupy complete page just occupies center part(its horizontal space depends on sum of child elements, in this case it wont add up to fill up whole page.

Just change the HorizontalAlignment = "Stretch" so that whole space available and individual grid components occupy half space.

<Grid HorizontalAlignment="Stretch" >
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Button Grid.Column="0"
                Content="This is a wide button"
                HorizontalAlignment="Center" />
        <Button Grid.Column="1"
                Content="Button"
                HorizontalAlignment="Center"/>
    </Grid>

Image:

enter image description here

like image 156
Morse Avatar answered Jan 02 '26 16:01

Morse


The Windows Community Toolkit has a Uniform Grid control you can use if you add in the NuGet package.

like image 29
Johnny Westlake Avatar answered Jan 02 '26 18:01

Johnny Westlake



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!