Xamarin CollectionView equal item width with HorizontalItemSpacing

Viewed 879

I would like to display items from List as displayed in FlexLayout. I want that items has the same width and the same Horizontal and Vertical-Spacing. The image bellow shows the an example.

FlexLayout

I tried using CollectionView, my XAML is looking as follows:

<CollectionView ItemsSource="{Binding Cards}" Margin="10,10,10,10"
                >
    <CollectionView.ItemsLayout>
        <GridItemsLayout Orientation="Vertical" Span="3"
                         HorizontalItemSpacing="10"
                         VerticalItemSpacing="10"
                         />
    </CollectionView.ItemsLayout>
    <CollectionView.ItemTemplate>
        <DataTemplate>
            <Grid HeightRequest="200" BackgroundColor="{Binding BackGroundColor}">
                <Label Text="{Binding Text}"/>
            </Grid>
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

This kind of works, except that the width of the items is somehow off and looks as follows: cards of set

I tried using ItemSizingStrategy="MeasureFirstItem" but it did not work as I wanted.

Is there better way to achieve it ?

Thank you all for your help.

1 Answers

There are many solution which can implement it . For example you could create a custom StackLayout .

public class SquareView : StackLayout
{
    protected override void OnSizeAllocated(double width, double height)
    {
        base.OnSizeAllocated(width, height);
        HeightRequest = Width;
    }
}

in xaml

 <CollectionView x:Name="list" Margin="10,10,10,10">
    <CollectionView.ItemsLayout>
        <GridItemsLayout Orientation="Vertical" Span="3"
                     
                     />
    </CollectionView.ItemsLayout>
    <CollectionView.ItemTemplate>
        <DataTemplate>
            <Grid Padding="5">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>

                <Grid.RowDefinitions>

                    <RowDefinition Height="Auto" />

                </Grid.RowDefinitions>


                <local:SquareView BackgroundColor="LightBlue">
                    <Label Text="11111" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" />
                </local:SquareView>


            </Grid>
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>
Related