[英]Correct method to update the observable collection?
Here is the story 这是故事
// This is the sample class //这是示例类
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});
I then added above collection to the ListView. 然后,我将上述集合添加到ListView中。
ListView LView = new ListView();
ListView.ItemsSource = CarList;
Next I have a button that will update the collection item with name "Honda". 接下来,我有一个按钮,它将以名称“ Honda”更新收集项。 I want to update the count value by +1.
我想将计数值更新+1。
Here is what I did on the Button Click event: 这是我对Button Click事件所做的事情:
First method: 第一种方法:
I got the index in the collection by searching the list with value "Honda" in it. 我通过在列表中搜索值“ Honda”获得索引。 And I updated the value to that index like this:
我将值更新为该索引,如下所示:
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;
Second method: 第二种方法:
I collected the values in a temporary list for the current index. 我将这些值收集在当前索引的临时列表中。
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]);
The second method updated the ListView. 第二种方法更新了ListView。
Give me the best and correct solution for updating the list 给我最好和正确的解决方案来更新列表
Implement INotifyPropertyChanges
in your "Car" type. 在您的“汽车”类型中实现
INotifyPropertyChanges
。 Here is an example of how to do it. 这是一个如何做的例子 。
ObservableCollection subscribes to this interface event, so when your Car.count property raises PropertyChanged event, ObservableCollection can see it and can notify the UI, so UI will refresh. ObservableCollection订阅此接口事件,因此,当您的Car.count属性引发PropertyChanged事件时,ObservableCollection可以查看该事件并可以通知UI,因此UI会刷新。
You are not updating the Observable collection. 您没有更新Observable集合。
You are updating an object in the collection. 您正在更新集合中的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.