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>
Related videos on Youtube
Author by
Denys Wessels
Updated on October 18, 2022Comments
-
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 asTheyAreAllNextToEachOther
.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 over 10 yearsJust so that you know the difference between the two answers that you have currently been provided with, the
ItemContainerStyle
is aStyle
for the 'item container', or theListBoxItem
if you were using aListBox
. TheItemTemplate
is aDataTemplate
that defines what the 'contents' of the items should look like. Therefore, in theItemContainerStyle
, you can access properties of the container (eg. ListBoxItem.IsSelected) and in theDataTemplate
, you can access the public class properties of the data item.
-
-
Julien about 10 yearsWhile 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 about 8 yearsIf you want a spacing of 3 you can set left and right margin at 1.5... just saying
-
grek40 almost 8 yearsIf 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 almost 7 yearsNot advised to use data template for this in practice. If all you care about is the margin itemcontainer is much better.