简体   繁体   中英

Xamarin Listview binding to ObservableCollection of normal class

I have been supplied with a Book class which is not implemented the INotifyPropertyChanged interface and I can't change it. I have a collection of Book which I want to show in a ListView in Xamarin. So:

public class BookListViewModel : INotifyPropertyChanged
{
    public ObservableCollection<Book> Books { get; set; }

    private void TestAction()
    {
        Books[1].Name = "New Name";
        //Here I need to inform the list to refresh
    }
}

Now I bind this Books to my ListView.ItemsSource . How can I inform the ListView to refresh? I have tried placing OnPropertyChanged("Books"); where the comment is but not luck.

When you try OnPropertyChanged("Books"); this is used for notify the list that the count of the elements has been changed and not the elements themselves .

As you cannot implement the INotifyPropertyChanged on the model level, the trick is to when you modify a cell in the list in your case:

  1. Remove the element you want to modify
  2. Call OnPropertyChanged("Books"); so the list would be refreshed
  3. Add the element you want to modify with the new data
  4. Call OnPropertyChanged("Books"); so the list would be refreshed with the cell updated.

As you might guess this solutiom might solve your problem but performance wise is bad , since you have the viewlist has to be redrawn twice. So if the class Book is changable frequently then I would say that you have to change it to make it implementing INotifyPropertyChanged

Or you might have a middle copy of Book class that would implement INotifyPropertyChanged and has an instance of Book that you refer to its properties from the riplica class. You can use Automapper to help you with that by the way if you have many classes to deal with

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM