简体   繁体   中英

Xamarin CollectionView equal item width with HorizontalItemSpacing

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.

弹性布局

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: 套牌

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM