Setting a GroupHeader or Footer from C# creates hundreds of subviews to CollectionView

Niklas Blomstrand 1 Reputation point
2022-01-28T15:12:03.567+00:00

Hi,

I have a CollectionView where I want to show grouped data.
After following the example in the documentation I have a List<TemplateGroup> where TemplateGroup inherits from List<Template> and has a Name property. Just like the documentations example with AnimalGroup/Animal.

It works fine until I try to set GroupHeaderTemplate or GroupFooterTemplate. If any of these are set and I scroll up and down in the collection view, hundreds of childviews to the collectionview are created. The views that are created are not visible but are instances of the type of view that I have set as GroupHeaderTemplate and it impacts the performance of the collectionview a lot.

Here is the code from my views constructor:

            _templateGroupCollection = new CollectionView
            {
                IsGrouped = true,
                ItemsLayout = new GridItemsLayout(4, ItemsLayoutOrientation.Vertical)
                {
                    HorizontalItemSpacing = 10,
                    VerticalItemSpacing = 10
                },
                ItemTemplate = new DataTemplate(typeof(TemplateItemGridView)),
                GroupHeaderTemplate = new DataTemplate(() =>
                {
                    var nameLabel = new Label();
                    nameLabel.SetBinding(Label.TextProperty, "Name");

                    return nameLabel;
                }),
                GroupFooterTemplate = new DataTemplate(typeof(Label)),
               };

            _templateGroupCollection.SetBinding(ItemsView.ItemsSourceProperty, new Binding("TemplateGroups", source: ViewModel));

As I said, this works fine if GroupHeaderTemplate or GroupFooterTemplate is not set.
I would love some input as to what might be able to cause this kind of issue.

I just tested in a new Multiplatform project with the ViewModel from the documentation but with my CollectionView in C# and I get the same result.
If I use the Xaml from the documentation instead of my C# code it seems to work fine.
I will try to convert my own view to Xaml as well to see if I can use that as a workaround, I'm still curios as to what is happening here though.

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