Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 58056

Strange behavior with re-using listview items when adding items to an ObservableCollection

$
0
0

Here's my situation. I have a listview that I bind to a source using:
_listView.SetBinding(ListView.ItemsSourceProperty, vm => vm.MyItems);

I'm asynchronously loading the items

public async Task LoadItems()
{
    var items = await GetItems();

    // Method 1: This works fine
    Items = new ObservableCollection<MyViewModel>(from i in items select new MyViewModel(i));

    // Method 2: This doesn't work as expected
    Items.Clear();
    foreach (var item in items)
    {
        var myViewModel = new MyViewModel(item);
        Items.Add(myViewModel);
    }
}

My listview uses a DataTemplate and I have some Debug.WriteLine statements in there to see when the template is instantiated. I'm loading about 50 items.

Using Method 2 I see that ALL 50 items are retrieved and that a DataTemplate is instantiated for all these 50 items. Only after all 50 DataTemplates are instantiated it shows the listview.

Using Method 1 I see that all 50 items are retrieved but only the first 5 DataTemplates (for the items that are visible on the screen) are instantiated and only when I scroll down it will instantiate the next DataTemplates.

It seems that only Method 1 makes use of the listitem virtualization mechanism of the ListView which results in a much better performance.

Does anyone know why these 2 methods of filling the ObservableCollection are different?

Thanks,
Jeffry


Viewing all articles
Browse latest Browse all 58056

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>