WPF Grid Center and Stretch Textbox


I have a WPF grid with row and column 0 as labels. I want the first column to be a static value of 20, but I want the rest of the columns to stretch to their available space until they hit the max width and I want the grid to remain centered even after the rows have hit their max. If I use Grid HorizontalAlignment="Center" each column width is equal to the width of the content of that row, which doesn't look very good for a column full of empty text boxes. If I use Grid HorizontalAlignment="Stretch" it does exactly what I want it to but the Grid isn't centered after the columns have reached their max width, it's left aligned. Is there any way to center the grid and stretch the columns? Attached is a section of the xaml for my grid.


<Expander Margin="10,10,10,10" Header="Expander">
    <Grid Margin="10,10,10,10" HorizontalAlignment="Center">
            <ColumnDefinition Width="20" />
            <ColumnDefinition Width="*" MaxWidth="200"/>
            <ColumnDefinition Width="*" MaxWidth="200" />
            <ColumnDefinition Width="*" MaxWidth="200" />
             <RowDefinition />
             <RowDefinition />
         <Label Content="Ax" HorizontalContentAlignment="Center" Grid.Column="1" Grid.Row="0"/>
         <Label Content="0" HorizontalContentAlignment="Center" VerticalAlignment="Center" Grid.Column="0" Grid.Row="1" />
         <TextBox Name="AxK00" Margin="1,1,1,1" HorizontalContentAlignment="Center" Grid.Column="1" Grid.Row="1" />
         <TextBox Name="AyK00" Margin="1,1,1,1" HorizontalContentAlignment="Center" Grid.Column="2" Grid.Row="1" />
         <TextBox Name="AzK00" Margin="1,1,1,1" HorizontalContentAlignment="Center" Grid.Column="3" Grid.Row="1" />

Best Answer

While your columns have reached their MaxWidth the Grid has a HorizontalAlignment=Stretch which means the Grid is going to expand to fill the space unless you give it a Width. Try setting your Grid's MaxWidth to 620 (the sum of your MaxWidths) or something similar. Your Grid will stretch to fill your max size, but still be small enough for the HorizontalAlignment =Center to be observable.

Related Topic