简体   繁体   English

Xamarin Listview绑定到普通类的ObservableCollection

[英]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. 我提供了一个Book类,该类未实现INotifyPropertyChanged接口,因此无法更改。 I have a collection of Book which I want to show in a ListView in Xamarin. 我有一个要在Xamarin的ListView中显示的Book的集合。 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 . 现在我结合这个BooksListView.ItemsSource How can I inform the ListView to refresh? 如何通知ListView刷新? I have tried placing OnPropertyChanged("Books"); 我曾尝试放置OnPropertyChanged("Books"); where the comment is but not luck. 评论在哪里,但不是运气。

When you try OnPropertyChanged("Books"); 当您尝试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: 由于您无法在模型级别上实现INotifyPropertyChanged ,因此诀窍在于修改案例中的列表中的单元格:

  1. Remove the element you want to modify 删除要修改的元素
  2. Call OnPropertyChanged("Books"); 调用OnPropertyChanged("Books"); so the list would be refreshed 所以列表会刷新
  3. Add the element you want to modify with the new data 使用新数据添加要修改的元素
  4. Call OnPropertyChanged("Books"); 调用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 因此,如果Book类经常更改,那么我会说您必须对其进行更改以使其实现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. 或者,您可能具有Book类的中间副本,该副本将实现INotifyPropertyChanged并具有一个Book实例,您可以从riplica类中引用其属性。 You can use Automapper to help you with that by the way if you have many classes to deal with 如果您有很多要处理的类,可以使用Automapper来帮助您

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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