2014-02-14 66 views
0

有沒有辦法在ObservableCollection中添加新項目或更新現有項目時獲取通知或事件。說如何在ObservableCollection對象中獲取更改通知

class Notify:INotifyPropertyChanged 
{ 
    private string userID { get; set; } 
    public string UserID 
    { 
     get { return userID; } 

     set 
     { 
      if (userID != value) 
      { 
       userID = value; 
       OnPropertyChanged("UserID"); 
      } 
     } 
    } 
    public event PropertyChangedEventHandler PropertyChanged; 
    private void OnPropertyChanged(string propertyName) 
    { 
     PropertyChangedEventHandler handler = PropertyChanged; 
     if (handler != null) 
      handler(this, new PropertyChangedEventArgs(propertyName)); 
    } 
} 

class MainClass 
{ 

    ObservableCollection<Notify> notifyme = new ObservableCollection<Notify>(); 


changed() 
{ 
    //logic where there is an update 
} 

} 

當我稱()改變

回答

2

只有真正一個辦法做到這一點:掛鉤,在每個項目的事件處理程序(或之前),將其添加到的ObservableCollection。

notifyme.Add(new Notify{ PropertyChanged += (o, e) => { do whatever }}); 

這是因爲ObservableCollection只是一個容器,它的每個項目都必須單獨掛鉤。當然,你可以編寫自己的擴展類(或擴展方法)來幫助實現自動化。

1

我認爲INotifyPropertyChanged會通知propertychanged事件,但在這裏我認爲您的集合已更改。所以你必須提出一個CollectionChanged事件。

我建議你看看thisthis

希望這對你有所幫助!

1

您可以使用類似這樣

public class NotifyCollection 
{ 
    private readonly ObservableCollection<Notify> collection; 

    public NotifyCollection() 
    { 
     collection = new ObservableCollection<Notify>(); 
     collection.CollectionChanged += collection_CollectionChanged; 
    } 

    private void collection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) 
    { 
     if ((e.Action == NotifyCollectionChangedAction.Remove || e.Action == NotifyCollectionChangedAction.Replace) && e.OldItems != null) 
     { 
      foreach (var oldItem in e.OldItems) 
      { 
       var item = (Notify)oldItem; 
       try 
       { 
        item.PropertyChanged -= notify_changes; 
       } 
       catch { } 
      } 
     } 

     if((e.Action==NotifyCollectionChangedAction.Add || e.Action==NotifyCollectionChangedAction.Replace) && e.NewItems!=null) 
     { 
      foreach(var newItem in e.NewItems) 
      { 
       var item = (Notify)newItem; 
       item.PropertyChanged += notify_changes; 
      } 
     } 

     notify_changes(null, null); 
    } 

    private void notify_changes(object sender, PropertyChangedEventArgs e) 
    { 
     //notify code here 
    } 

    public ObservableCollection<Notify> Collection 
    { 
     get 
     { 
      return collection; 
     } 
    } 
} 
相關問題