が物語observableコレクションを更新する正しい方法はありますか?ここで
//これは、サンプル・クラス
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で更新したい。ここで
は、私はボタンのClickイベントにやったことです:
最初の方法:
私はそれに値「ホンダ」でリストを検索して、コレクション内のインデックスを得ました。そして、私はこのようにそのインデックスに値を更新:
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]);
2番目のメソッドは、ListViewを更新しました。
は、あなたの「車」タイプでINotifyPropertyChanges
を実装するリストに
INotifyPropertyChangesは、インターフェイスを更新するための全く異なる方法です。私はコレクションの更新イベントでいくつかのストーリーボードアニメーション効果を追加しました。 2番目の方法を使用すると、ListViewインターフェイスの変更された行に完全にアニメーションが適用されます。しかし、私はINotifyPropertyChangesを使用する場合、いくつかの微調整が必要になるかもしれません。 – user995387