更新可观测集合的正确方法

本文关键字:方法 集合 可观 更新 | 更新日期: 2023-09-27 18:24:58

这是的故事

//这是样品类

Public class Car {
    public string name {get;set;}
    public int count {get;set;}
}
//The Observable collection of the above class.
ObservableCollection<Car> CarList = new ObservableCollection<Car>();
// I add an item to the collection.
CarList.Add(new Car() {name= "Toyota", count = 1});
CarList.Add(new Car() {name= "Kia", count = 1});
CarList.Add(new Car() {name= "Honda", count = 1});
CarList.Add(new Car() {name= "Nokia", count = 1});

然后我将上面的集合添加到ListView中。

ListView LView = new ListView();
ListView.ItemsSource = CarList;

接下来我有一个按钮,它将更新名为"本田"的收藏项目。我想将计数值更新+1。

以下是我在按钮点击事件中所做的:

第一种方法:

我通过搜索列表中的值"Honda"得到了集合中的索引。我将值更新为这样的索引:

     CarList[index].count = +1;
// This method does not creates any event hence will not update the ListView.
// To update ListView i had to do the following.
LView.ItemsSource= null;
Lview.ItemsSource = CarList;

第二种方法:

我收集了当前索引的临时列表中的值。

index = // resulted index value with name "Honda".
string _name = CarList[index].name;
int _count = CarList[index].count + 1; // increase the count
// then removed the current index from the collection.
CarList.RemoveAt(index);
// created new List item here.
List<Car> temp = new List<Car>();
//added new value to the list.
temp.Add(new Car() {name = _name, count = _count});
// then I copied the first index of the above list to the collection.
CarList.Insert(index, temp[0]);

第二个方法更新了ListView。

给我更新列表的最佳和正确的解决方案

更新可观测集合的正确方法

在您的"Car"类型中实现INotifyPropertyChanges。下面是一个如何做到这一点的例子

ObservableCollection订阅了这个接口事件,所以当你的Car.count属性引发PropertyChanged事件时,Observable Collection可以看到它并通知UI,所以UI会刷新。

您没有更新Observable集合
您正在更新集合中的对象。