Jazzman
Jazzman

Reputation: 53

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

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)?

Upvotes: 2

Views: 2272

Answers (3)

Venkat
Venkat

Reputation: 140

Telerik RadDataGrid control will help you with your scenario

Add\install Telerik.UI.Xaml.Controls.Grid from Nuget inorder to use RadDataGrid in your UWP App

Upvotes: 0

Morse
Morse

Reputation: 9115

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

Upvotes: 6

Johnny Westlake
Johnny Westlake

Reputation: 1459

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

Upvotes: 3

Related Questions