2010-04-28 3 views

답변

2

아래 코드는 문제를 해결하는 방법의 예입니다. 이 예제에서 MyCollection은 ViewModel 객체의 속성입니다. ViewModel은 INotifyPropertyChanged 인터페이스를 구현합니다.

private void AddCollectionListener() 
    { 
     if (MyCollection != null) 
     { 
      MyCollection.CollectionChanged += 
       new System.Collections.Specialized.NotifyCollectionChangedEventHandler(MyCollection_CollectionChanged); 
     } 
    } 

    void MyCollection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) 
    { 
     // Remove Listeners to each item that has been removed 
     foreach (object oldItem in e.OldItems) 
     { 
      ViewModel viewModel = oldItem as ViewModel; 

      if (viewModel != null) 
      { 
       viewModel.PropertyChanged -= viewModel_PropertyChanged; 
      } 
     } 

     // Add Listeners to each item that has been added 
     foreach (object newItem in e.NewItems) 
     { 
      ViewModel viewModel = newItem as ViewModel; 

      if (viewModel != null) 
      { 
       viewModel.PropertyChanged += new PropertyChangedEventHandler(viewModel_PropertyChanged); 
      } 
     } 
    } 

    void viewModel_PropertyChanged(object sender, PropertyChangedEventArgs e) 
    { 
     // TODO: Property Changed Logic 

     switch (e.PropertyName) 
     { 
      case "MyPropertyName": 
       // TODO: Perform logic necessary when MyPropertyName changes 
       break; 
      default: 
       // TODO: Perform logic for all other property changes. 
       break; 
     } 
    } 
+0

데이터를 변조하는 방법을 보여주기 위해 코드를 편집했습니다. 개체의 추가 및 제거가 아닌 개체의 업데이트를 알 수 있습니까? – developer

+1

ViewModel의 속성 (PropertyChanged 이벤트를 발생시키는 모든 속성)이 변경 될 때마다 viewModel_PropertyChanged 처리기가 호출됩니다. 일반적으로 e.PropertyName을 켜는 switch 문을 추가합니다. MyPropertyName이 하나 이상의 ViewModel에있는 속성 인 예제를 보여주기 위해 코드를 업데이트했습니다. –

+0

soooo 많이 감사합니다 .. – developer

관련 문제