2012-02-18 7 views
0

여기이 내가 다음의 ListView에 수집 위에 추가 샘플 클래스관찰 가능한 컬렉션을 업데이트하는 올바른 방법은 무엇입니까?

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 LView = new ListView(); 
ListView.ItemsSource = CarList; 

다음으로 컬렉션 항목을 "혼다"라는 이름으로 업데이트하는 버튼이 있습니다. 카운트 값을 +1로 업데이트하고 싶습니다. 여기

내가 버튼을 클릭 이벤트에 무슨 짓을 :

첫 번째 방법 :

나는 그것을 가치 "혼다"로 목록을 검색하여 컬렉션의 인덱스를 얻었다. 그리고는 다음과 같이 해당 인덱스에 값을 업데이트 :

 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를 업데이트했습니다.

은 "자동차"유형의 INotifyPropertyChanges을 구현 목록을

답변

1

를 업데이트 나에게 최고의 올바른 솔루션을 지정합니다. 그것을하는 방법의 Here is an example.

ObservableCollection은이 인터페이스 이벤트를 구독하므로 Car.count 속성이 PropertyChanged 이벤트를 발생시킬 때 ObservableCollection에서이를 볼 수 있고 UI에 알릴 수 있으므로 UI가 새로 고침됩니다.

+0

INotifyPropertyChanges는 인터페이스를 업데이트하는 완전히 다른 방법으로 보입니다. 컬렉션 업데이트 이벤트에서 스토리 보드 애니메이션 효과를 추가했습니다. 두 번째 방법을 사용하면 ListView 인터페이스에서 변경된 행에 완벽하게 애니메이션을 적용합니다. 그러나 INotifyPropertyChanges를 사용하는 경우 약간의 조정이 필요할 수 있습니다. – user995387

0

Observable 컬렉션을 업데이트하지 않습니다.
컬렉션의 개체를 업데이트하고 있습니다.

+0

두 번째 방법이 될 수 있습니다. 컬렉션을 업데이트했습니다. – user995387

+1

예. 제거하고 삽입하는 것 같습니다. 컬렉션에 함수를 연결 한 코드는 표시하지 않습니다. 오래 전 관찰 가능한 컬렉션에 대한 블로그 게시물을 작성하여 도움을받을 수 있습니다. http://weblogs.asp.net/stevewellens/archive/2010/05/29/observable-collections.aspx –

관련 문제