List of checkboxes in collectionview taking long time to load

60 Views Asked by At

I need to show list of checkboxes to the screen. When I am trying to add it in collection view, it is taking lot time to load.

Below is the Source code. I have add only few items here in Items I do have around 500 items in the list.

View Model

public class CheckboxItem
    {
        public string Label { get; set; }
        public bool IsSelected { get; set; }
    }



Items = new ObservableCollection<CheckboxItem>
        {
             new CheckboxItem { Label = "Option 1", IsSelected = false },
                new CheckboxItem { Label = "Option 2", IsSelected = true },
                new CheckboxItem { Label = "Option 3", IsSelected = false },
                new CheckboxItem { Label = "Option 100", IsSelected = false }
        };

XAML

<CollectionView ItemsSource="{Binding Items}">
        <CollectionView.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto" />
                    </Grid.RowDefinitions>

                    <StackLayout Orientation="Horizontal" VerticalOptions="Center">
                        <CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay}" />
                        <Label Text="{Binding Label}" VerticalOptions="Center" Margin="10,0,0,0" />
                    </StackLayout>

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

Appreciate your help. Thanks !!

1

There are 1 best solutions below

0
FreakyAli On

What you need for starters is compiled bindings so you can make things smoother then you can optimize the rest of your code

Assuming your CheckboxItem is in whatever namespace you can reference that and then do this :

        <DataTemplate x:DataType="models:CheckboxItem">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                </Grid.RowDefinitions>

                <StackLayout Orientation="Horizontal" VerticalOptions="Center">
                    <CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay}" />
                    <Label Text="{Binding Label}" VerticalOptions="Center" Margin="10,0,0,0" />
                </StackLayout>

            </Grid>
        </DataTemplate>

I highly recommend you read these two blogs on mine for further help:

https://freakyali.medium.com/increasing-performance-in-a-net-maui-application-2be8ce7d995a

https://freakyali.medium.com/leveraging-the-power-of-compiled-bindings-in-net-maui-4b3db6b9f4cb