How can I make a Xamarin Forms CollectionView size to fit its contents?

Viewed 750

I'm using a Xamarin Forms CollectionView to present a grouped list of items. Each item is rendered with a DataTemplate that has a fixed height, and each group header is rendered with another DataTemplate that has a fixed height.

How can I make the CollectionView height big enough to accommodate all of its contents (items, group headers and spaces inbetween) without having to be scrolled, and without hard-coding the height?

Here's my XAML. I've omitted the contents of the grids for brevity.

<CollectionView
    IsGrouped="True"
    ItemsSource="{Binding Items}"
    SelectedItems="{Binding SelectedItems}"
    SelectionMode="Multiple">
    <CollectionView.ItemsLayout>
        <LinearItemsLayout
            ItemSpacing="10"
            Orientation="Vertical" />
    </CollectionView.ItemsLayout>
    <CollectionView.GroupHeaderTemplate>
        <DataTemplate>
            <Grid HeightRequest="20" />
        </DataTemplate>
    </CollectionView.GroupHeaderTemplate>
    <CollectionView.ItemTemplate>
        <DataTemplate>
            <Grid HeightRequest="90" />
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

Note that I can't use BindableLayout or ListView because I need the grouping and multiple selection. I'd also like to do this without breaking the MVVM abstraction, so ideally I don't want anything in the view model to know anything about row heights.

Any help much appreciated.

1 Answers

Wrap it with AbsoluteLayout so you can set Height and Width
by % of screen size or the AbsoluteLayout parent layout size

and then set the HorizontalOption and VerticalOption
of your CollectionView to FillAndExpand

Related