[英]Correct method to update the observable collection?
这是故事
//这是示例类
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;
接下来,我有一个按钮,它将以名称“ Honda”更新收集项。 我想将计数值更新+1。
这是我对Button Click事件所做的事情:
第一种方法:
我通过在列表中搜索值“ 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。
给我最好和正确的解决方案来更新列表
您没有更新Observable集合。
您正在更新集合中的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.