Item spacing in WPF ItemsControl

18,586

Solution 1

I'd add an ItemTemplate where you set the margin

<ItemsControl.ItemTemplate>
    <DataTemplate>
        <TextBlock Margin="3,3,3,3" Text="{Binding}"/>
   </DataTemplate>
</ItemsControl.ItemTemplate>

Solution 2

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>
Share:
18,586

Related videos on Youtube

Denys Wessels
Author by

Denys Wessels

Updated on October 18, 2022

Comments

  • Denys Wessels
    Denys Wessels over 1 year

    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>
    
    • Sheridan
      Sheridan over 10 years
      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.
  • Julien
    Julien about 10 years
    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.
  • Mauro Sampietro
    Mauro Sampietro about 8 years
    If you want a spacing of 3 you can set left and right margin at 1.5... just saying
  • grek40
    grek40 almost 8 years
    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: <WrapPanel IsItemsHost="True" Orientation="Horizontal" Margin="-3,-3,-3,-3"/> in case of this answer with an item gap of 6.
  • Wobbles
    Wobbles almost 7 years
    Not advised to use data template for this in practice. If all you care about is the margin itemcontainer is much better.