17

I'm displaying a List<string> collection in an ItemsControl. The problem is that there is no spacing between the list items such as TheyAreAllNextToEachOther.

How can I create some spacing between the items?

<ItemsControl Grid.Column="2" 
         Grid.ColumnSpan="2" 
         ItemsSource="{Binding Path=ShowTimes}"
         BorderThickness="0">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel IsItemsHost="True" Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>
ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
Denys Wessels
  • 16,829
  • 14
  • 80
  • 120
  • 5
    Just so that you know the difference between the two answers that you have currently been provided with, the `ItemContainerStyle` is a `Style` for the 'item container', or the `ListBoxItem` if you were using a `ListBox`. The `ItemTemplate` is a `DataTemplate` that defines what the 'contents' of the items should look like. Therefore, in the `ItemContainerStyle`, you can access properties of the container (eg. ListBoxItem.IsSelected) and in the `DataTemplate`, you can access the public class properties of the data item. – Sheridan Jan 07 '14 at 12:53

2 Answers2

75

Provide style to your ItemsControl containers (default ContentPresenter) like this where you can set Margin to say 5:

    <ItemsControl>
        <ItemsControl.ItemContainerStyle>
            <Style>
                <Setter Property="FrameworkElement.Margin" Value="5"/>
            </Style>
        </ItemsControl.ItemContainerStyle>
    </ItemsControl>
Rohit Vats
  • 79,502
  • 12
  • 161
  • 185
3

I'd add an ItemTemplate where you set the margin

<ItemsControl.ItemTemplate>
    <DataTemplate>
        <TextBlock Margin="3,3,3,3" Text="{Binding}"/>
   </DataTemplate>
</ItemsControl.ItemTemplate>
Clemens
  • 123,504
  • 12
  • 155
  • 268
gomi42
  • 2,449
  • 1
  • 14
  • 9
  • 7
    While this does work and is similar to pretty much every other solution out there, it's not ideal. If there is only one item, you are adding spacing for nothing, and the first and last item will always have extra space. This also means that each element has an effective spacing of 6, because the previous element will always have a margin of 3 existing already. – Julien Apr 15 '14 at 17:25
  • If you want a spacing of 3 you can set left and right margin at 1.5... just saying – Mauro Sampietro Feb 26 '16 at 15:43
  • 8
    If you just want gaps without outer spacing of the items control, set negative margins to the item panel, equal to the positive margin of the items: `` in case of this answer with an item gap of 6. – grek40 Jun 17 '16 at 08:11
  • 1
    Not advised to use data template for this in practice. If all you care about is the margin itemcontainer is much better. – Wobbles Jun 23 '17 at 14:08