.

Spacing (styling) child elements in WPF

You can style your WPF child elements as follow:

<StackPanel Orientation="Horizontal" HorizontalAlignment="Left" DockPanel.Dock="Top"  >
    <StackPanel.Resources>
        <Style TargetType="{x:Type Button}">
            <Setter Property="Margin" Value="10,10,0,10"/>
        </Style>
    </StackPanel.Resources>

    <Button Content="Button" Width="75"/>
    <Button Content="Button" Width="75"/>
</StackPanel>

Another quick way to do something similar:

<StackPanel local:MarginSetter.Margin="5">
   <TextBox Text="hello" />
   <Button Content="hello" />
   <Button Content="hello" />
</StackPanel>

In case you would want to re-use the margin between two containers, you can convert the margin value to a resource in an outer scope, f.e.

<Window.Resources>
    <Thickness x:Key="tbMargin">0,10,0,0</Thickness>
</Window.Resources>

and then refer to this value in the inner scope

<StackPanel.Resources>
    <Style TargetType="{x:Type TextBox}">
        <Setter Property="Margin" Value="{StaticResource tbMargin}"/>
    </Style>
</StackPanel.Resources>

 

What's your thoughts on this?

*

Protected by WP Anti Spam