Automatic Sizing For CollectionView

Nathan Sokalski 4,116 Reputation points
2020-11-30T21:06:04.127+00:00

I have several CollectionView(s) which I want to be automatically sized to the height of their items (the CollectionView(s) are horizontal). However, they are instead using the full height. Here is the code for my CollectionView:

<CollectionView x:Name="itmPlayerNames" Grid.Column="1" Grid.Row="0" BackgroundColor="Blue" HorizontalOptions="Start" VerticalOptions="Start" HorizontalScrollBarVisibility="Never" VerticalScrollBarVisibility="Never">
<CollectionView.ItemsSource>
<x:Array Type="{x:Type system:String}">
<system:String>Player One</system:String>
<system:String>Player Two</system:String>
<system:String>Player Three</system:String>
<system:String>Player Four</system:String>
<system:String>Player Five</system:String>
<system:String>Player Six</system:String>
</x:Array>
</CollectionView.ItemsSource>
<CollectionView.ItemsLayout><LinearItemsLayout Orientation="Horizontal"/></CollectionView.ItemsLayout>
<CollectionView.ItemTemplate><DataTemplate><Label Text="{Binding}" Style="{StaticResource ItemText}" HorizontalTextAlignment="Center" BackgroundColor="Green"/></DataTemplate></CollectionView.ItemTemplate>
</CollectionView>

How can I make this be the height of the items in the DataTemplate? I am very confused by some of the properties like VerticalOptions, HeightRequest, etc. I found everything in UWP much easier with properties like Height & VerticalAlignment. Any ideas? Thanks.

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,293 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 68,491 Reputation points Microsoft Vendor
    2020-12-01T06:25:18.403+00:00

    Hello,​

    Welcome to our Microsoft Q&A platform!

    Items in a CollectionView can be dynamically resized by changing layout related properties of elements within the DataTemplate.

    In your DataTemplate, you just have Label, if you want to change the Height, you could set HeightRequest for your Label

       <Label HeightRequest="300"  Text="{Binding .}"   BackgroundColor="Green"/>  
    

    Here is related article about it.
    https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/collectionview/layout#dynamic-resizing-of-items

    Best Regards,

    Leon Lu


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.