#411 – Use HorizontalAlignment and VerticalAlignment to Position Child Elements within a Grid

By default, the HorizontalAlignment and VerticalAlignment properties of child elements in a Grid are set to Stretch.  This value indicates that the child element should be sized to fit the containing cell. In the example below, the labels and the button are all stretched to fit the containing cells.

You can set the alignment properties to other values, however.  HorizontalAlignment can be set to Stretch, Left, Center or RightVerticalAlignment can be set to Stretch, Top, Center or Bottom.

        <Label Grid.Row="0" Grid.Column="0" Content="Larry" Margin="5" Background="Lavender" HorizontalAlignment="Center" />
        <Label Grid.Row="0" Grid.Column="1" Content="Moe" Margin="5" Background="Magenta" VerticalAlignment="Center" />


The “Larry” label is still stretched vertically, but now centered horizontally.  The size of the label is also adjusted to fit the content.  The “Moe” label is still stretched horizontally, but now centered vertically.

Advertisements