Reputation: 385
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 LView = new ListView();
ListView.ItemsSource = CarList;
Next I have a button that will update the collection item with name "Honda". I want to update the count value by +1.
Here is what I did on the Button Click event:
First method:
I got the index in the collection by searching the list with value "Honda" in it. 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.
Give me the best and correct solution for updating the list
Upvotes: 0
Views: 597
Reputation: 20640
You are not updating the Observable collection.
You are updating an object in the collection.
Upvotes: 0
Reputation: 7535
Implement INotifyPropertyChanges
in your "Car" type. 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.
Upvotes: 1