Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Buttons do not stetch to fill Grid cells?

Tags:

xaml

uwp

I am about to create a Grid Matrix in a UWP application and came across this behavior where the Button control does not stretch to fill the available space; in contrast, the TextBox control does. How to force the Button control to behave like a TextBox?

     <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Grid.Resources>
            <Style TargetType="Button">
                <Setter Property="BorderBrush" Value="Yellow" />
                <Setter Property="BorderThickness" Value="5" />
            </Style>

            <Style TargetType="TextBox">
                <Setter Property="BorderBrush" Value="Yellow" />
                <Setter Property="BorderThickness" Value="5" />
            </Style>
        </Grid.Resources>

        <TextBox   Grid.Row="0" Grid.Column="0" Text="One"   />
        <TextBox  Grid.Row="0"  Grid.Column="1" Text="Two"   />

        <Button   Grid.Row="1" Grid.Column="0" Content="Three"   />
        <Button  Grid.Row="1"  Grid.Column="1" Content="Four"   />
    </Grid>

enter image description here

like image 891
usefulBee Avatar asked May 18 '17 18:05

usefulBee


1 Answers

Just add those two properties to your buttons:

HorizontalAlignment="Stretch"

VerticalAlignment="Stretch"

Final buttons definitons:

<Button
    Grid.Row="1"
    Grid.Column="0"
    HorizontalAlignment="Stretch"
    VerticalAlignment="Stretch"
    Content="Three" />
<Button
    Grid.Row="1"
    Grid.Column="1"
    HorizontalAlignment="Stretch"
    VerticalAlignment="Stretch"
    Content="Four" />

Also, the reason those properties need to be overwritten is because in the default Style Template for Button they are set via Setter as Left/Center respectively by default.

like image 65
Francesco Bonizzi Avatar answered Nov 07 '22 16:11

Francesco Bonizzi