How to update item in CollectionView properly?

Stesvis 1,041 Reputation points
2021-02-15T18:31:34.667+00:00

I have a CollectionView with:

ItemsSource="{Binding MyListings}"

where MyListings is:

[Reactive] public ObservableCollection<ListingDTO> MyListings { get; set; }

There are times when I need to programmatically add or remove items from the collection using MyListings.Add(...) or MyListings.Remove(...) and the UI is updated correctly.

There are other times where I just need to replace an item:

var index = MyListings.ToList().FindIndex(x=>x.Id == updatedListing.Id);
MyListings[index] = updatedListing;

I can see that the item in MyListings has been updated properly, but the UI does not update, even if I put that code in Device.BeginInvokeOnMainThread(() =>{ ... });

It only works if I make a copy of MyListings like this, and then reset the whole collection:

var listings = MyListings.ToList();
var index = listings.ToList().FindIndex(x=>x.Id == updatedListing.Id);
listings[index] = updatedListing;

MyListings = new ObservableCollection<ListingDTO>(listings);

But it seems very inefficient. What is the correct way to update one item and see the changes update the UI too?
Thanks.

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

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.