74

I am trying to set padding of a StackPanel but there ain't such property. I tried StackPanel.Border, but there is no such property either.

Any ideas?

Shimmy Weitzhandler
  • 92,920
  • 119
  • 388
  • 596

5 Answers5

123

You could put a Border around the StackPanel and set a padding on that. I end up doing this a lot, since there are many UIElements that do not have a padding property.

<Border Padding="10">
    <StackPanel>
        <!--...-->
    </StackPanel>
</Border>

(Note: all FrameworkElements have a Margin property, which will space the element, but not include the margin width as part of the ActualWidth).

If you want to space the items inside a StackPanel, you'll want to add a margin to each child as Rob said.

KyleMit
  • 45,382
  • 53
  • 367
  • 544
Tim Swast
  • 12,039
  • 4
  • 35
  • 51
7

Or you could do something similar to TiM:

<Border>
    <StackPanel Margin="10">
        ...
    </StackPanel>
</Border>
KyleMit
  • 45,382
  • 53
  • 367
  • 544
Oliver
  • 30,713
  • 10
  • 54
  • 69
6

if you mean you want to space out child elements of the StackPanel (which doesn't have a Padding property), see: How do I space out the child elements of a StackPanel?

Community
  • 1
  • 1
George Birbilis
  • 663
  • 7
  • 3
3

You'll probably want to add margin to the items in the panel instead. You'll get the same result, just have to approach it backward.

Rob
  • 1,335
  • 1
  • 8
  • 14
  • 5
    you saying doing in it one place is worse than adding margin to dozen elements inside stackpanel? – Califf Mar 07 '13 at 16:41
  • No.. he's saying that it's the next easiest way, seeing as the StackPanel _doesn't actually have a Padding property_. – TernaryTopiary Oct 26 '16 at 08:51
3

This is a variant of padding for elements of StackPanel

<StackPanel Orientation="Horizontal" Grid.Row="2">
    <StackPanel.Resources>
         <Style x:Key="StackPanelPadding" TargetType="Control">
            <Setter Property="Margin" Value="5,0,0,0"/>
            <Setter Property="Height" Value="40"/>
         </Style>
         <Style BasedOn="{StaticResource StackPanelPadding}" TargetType="Button"/>
    </StackPanel.Resources>
    <Button/>
    <Button/>
</StackPanel>
KyleMit
  • 45,382
  • 53
  • 367
  • 544
Microshine
  • 651
  • 3
  • 18
  • 1
    This is okay, but it would override (or wouldn't) any margin you try to set on your buttons. That might be okay, but you're losing flexibility here. Also, if you want a style to apply to all controls within a resource scope, then just don't use an `x:Key`. So setting two styles here is unnecessary. Remove the second one (with `BasedOn`) and get rid of the `x:Key` attribute on the first. If you want it to only apply to buttons, then use that as the target type, otherwise you can leave it as is. – KyleMit Jan 31 '14 at 13:22