Search code examples
maui

Item spacing in a CollectionView when set to HorizontalList


How do we set the spacing between items in a CollectionView in a .NET MAUI app when we set ItemsLayout to HorizontalList.

I actually use a Border around each item so I thought I could achieve it by setting the Border margin to Margin="0,0,5,0" but that didn't work.

Here's my code for CollectionView:

<CollectionView
   ItemsSource="{Binding MyOptions}"
   ItemsLayout="HorizontalList"
   HeightRequest="30"
   <CollectionView.ItemTemplate>
      <DataTemplate
         x:DataType="itemoption:MyModel">
       <Border
            BackgroundColor="{StaticResource Gray}"
            StrokeShape="RoundRectangle 3"
            Padding="10">
            <Label
               Text="{Binding Name}"
               TextColor="{StaticResource Black}"
               FontSize="11"
               FontAttributes="Bold"
               HorizontalTextAlignment="Center"
               VerticalTextAlignment="Center" />
         </Border>
      </DataTemplate>
   </CollectionView.ItemTemplate>
</CollectionView>

This is what it looks like now and I just want more separation between items. enter image description here


Solution

  • You can use the ItemSpacing property for that:

    <CollectionView
        ItemsSource="{Binding MyOptions}"
        ItemsLayout="HorizontalList"
        ItemSpacing="20">
        <!-- ... -->
    </CollectionView>
    

    You can find more info on ItemSpacing in the official documentation.