#323 – Provide Space Around StackPanel Children Using Margin

By default, StackPanel provides no extra space around the child controls that it contains, but packs them tightly.

    <StackPanel>
        <Label Content="Gene Autry the singing cowboy" Background="Pink"/>
        <Button Content="I Like Gene" />
        <Label Content="Roy Rogers" Background="Aqua"/>
        <Button Content="I Like Roy Rogers Yes I Do"/>
        <Label Content="Spade Cooley had a sad story" Background="DodgerBlue"/>
    </StackPanel>


You can specify a margin that should be used around the outside of each control using the Margin property.

    <StackPanel>
        <Label Content="Gene Autry the singing cowboy" Background="Pink" Margin="5"/>
        <Button Content="I Like Gene" Margin="5"/>
        <Label Content="Roy Rogers" Background="Aqua" Margin="5"/>
        <Button Content="I Like Roy Rogers Yes I Do" Margin="5"/>
        <Label Content="Spade Cooley had a sad story" Background="DodgerBlue" Margin="5"/>
    </StackPanel>

In this example, we used a single value whenever we set the Margin property.  This causes the container to add the specified margin (in WPF units) along all four sides of the child control.

Advertisements