Search code examples
wpfxamllayoutmargin

margin best practise


If I have a Horizontal StackPanel with many elements, with different margin between them:

Is there any difference if I give each element a left margin or is there some advantage giving every second element a right and left margin - that way only one element gets its margin property set.

<StackPanel Orientation="Horizontal">
<TextBlock Name="textblock1" />
<TextBlock Name="textblock2" Margin="5,0,0,0" />
<TextBlock Name="textblock3" Margin="10,0,0,0" />
...
</StackPanel>

or

<StackPanel Orientation="Horizontal">
<TextBlock Name="textblock1" />
<TextBlock Name="textblock2" Margin="5,0,10,0" />
<TextBlock Name="textblock3" />
...
</StackPanel>

I was just wondering if there was a best-practise concerning this.


Solution

  • If the Margin is the same for every element, you can factor it out in a style:

    <StackPanel Orientation="Horizontal">
       <StackPanel.Resources>
          <Style TargetType="TextBlock>
             <Setter Property="Margin" Value="5,0,0,0" />
          </Style>
       </StackPanel.Resources>
       <TextBlock Name="textblock1" />
       <TextBlock Name="textblock2" />
       <TextBlock Name="textblock3" />
       ...
    </StackPanel>
    

    Other than that it makes no difference.