#323 – Provide Space Around StackPanel Children Using Margin
June 17, 2011 3 Comments
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.

Is there a way to do this using styles so that you don’t have to repeat the margin value?
Absolutely. That’s actually a good idea, because it moves that margin value into a single spot. Here’s the example re-written to use a style that just specifies the Margin:
<Window.Resources> <Style x:Key="smallMargin" TargetType="FrameworkElement"> <Setter Property="Margin" Value="5"/> </Style> </Window.Resources> <StackPanel> <Label Content="Gene Autry the singing cowboy" Background="Pink" Style="{StaticResource smallMargin}"/> <Button Content="I Like Gene" Style="{StaticResource smallMargin}"/> <Label Content="Roy Rogers" Background="Aqua" Style="{StaticResource smallMargin}"/> <Button Content="I Like Roy Rogers Yes I Do" Style="{StaticResource smallMargin}"/> <Label Content="Spade Cooley had a sad story" Background="DodgerBlue" Style="{StaticResource smallMargin}"/> </StackPanel>Pingback: #429 – Child Element Properties that Affect Layout « 2,000 Things You Should Know About WPF