#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:
Pingback: #429 – Child Element Properties that Affect Layout « 2,000 Things You Should Know About WPF