Xamarin removing CollectionView children

Viewed 39

I've got a problem with not refreshing GUI elements in the Xamarin's CollectionView.

The ObservableCollection Items binded to the CollectionView is cleared and filled with new elements during the RefreshingEvent but on the screen the old StackLayouts are shown.

The reason is that the SingleItem controls are not removed/deleted on Items.Clear() - how to do it?

<CollectionView x:Name="collection"
       ItemsSource="{Binding Items}"
       SelectionMode="None">
       <CollectionView.ItemTemplate>
            <DataTemplate>
                  <StackLayout>
                       <controls:SingleItem/>
                       <Grid BackgroundColor="White" HeightRequest="5" HorizontalOptions="Fill" VerticalOptions="End"/>
                  </StackLayout>
            </DataTemplate>
       </CollectionView.ItemTemplate>
</CollectionView>

C# - nothing "unusual" and this works alright (on breakpoints):

void RefreshCommand()
{
    List<Item> items = null;
    items = GetItems();
    if (items != null)
    {
        Items.Clear();
        foreach (var item in items)
            Items.Add(item);
    }
}

Wait, before You go forward, because below I wrote my "idea" how to solve it.

The problem is that I found no "Clear" or "Remove" method of GUI AllChildren - which is a internal member of Element:

void RefreshCommand(Action clearCollectionView)
{
    List<Item> items = null;
    items = GetItems();
    if (items != null)
    {
        Items.Clear();
        cleacCollectionView.Invoke();
        foreach (var item in items)
            Items.Add(item);
    }
}
// page.xaml.cs:
...
        BindingContext = new Model(() => ???);
...
1 Answers

You can write the Grid like this and bind the ObservableCollection data to the label instead of using the <controls:SingleItem/>

  <CollectionView  x:Name="Collection"  ItemsSource="{Binding Items}">
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <Grid BackgroundColor="White" HeightRequest="5" HorizontalOptions="Fill" VerticalOptions="End">
                       
                        <Label
                                Text="{Binding itemName}"
                                FontAttributes="Bold"
                                x:Name="labelname" VerticalTextAlignment="Center" HorizontalTextAlignment="Center"/>
                       
                    </Grid>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
Related