Forum Xamarin.Forms

Announcement:

The Xamarin Forums have officially moved to the new Microsoft Q&A experience. Microsoft Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

To create new threads and ask questions head over to Microsoft Q&A for .NET and get involved today.

Update item properties in a ListViews ObservableCollection

BastiBrauningBastiBrauning USMember ✭✭

I have a ListView which is bound to an ObservableCollection.

Is there a way to update a single cell whenever a property of a SomeModel item changed, without reloading the ListView by changing the ObservableCollection?

Best Answer

Answers

  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭

    I think you should implement NotifyPropertyChanged

  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭

    @adamkemp : perfect,as always

  • RanjanPRanjanP Member

    It does not works even if i remove and insert that element from "Items" observable collection and call OnPropertyChanged("Items");

    stumpted!!!

  • WelshDragonWelshDragon USMember

    @adamkemp : fabulous, works perfectly, Thank you

  • SteveShaw.5557SteveShaw.5557 USMember ✭✭✭
    edited December 2019

    @MichaelKapelko - I just discovered that it isn't necessary to create a custom subclass.
    Causing a list view's item to refresh itself is as simple as the following:

    In ViewModel, given property:

    public ObservableCollection<Item> Items { get; set; } = new ObservableCollection<Item>();
    

    After adding some items, suppose you want to cause item "item" to refresh itself:

    public void RefreshMe(Item item)
    {
        Items[Items.IndexOf(item)] = item;
    }
    

    That is, in the ObservableCollection, replace the item with itself.

    In my case, I had a TemplateSelector on the collection, and the item was changed in such a way that a different template was required. (Specifically, clicking on the item toggles it between collapsed view and expanded/detailed view, by the TemplateSelector reading an IsExpanded property from the model item.)

    NOTE: tested with a CollectionView, but AFAIK will also work with the older ListView class.
    Tested on iOS and Android.

  • SteveShaw.5557SteveShaw.5557 USMember ✭✭✭
    edited January 2020

    While the accepted answer by Adam Kemp is correct, I did not understand from what he said, nor from the doc he linked, how to do this.

    Almir Vuk gives a detailed implementation here.

    I recommend using that, instead of my answer immediately above. (Which works, but feels like a hack).

Sign In or Register to comment.