如何在ObservableCollection对象中获取有关更改的通知

时间:2014-02-14 04:50:04

标签: c# wpf

是否有办法在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
 }

}

何时调用changed()

3 个答案:

答案 0 :(得分:2)

实际上只有一种方法:在将每个项目添加到ObservableCollection之前(或之前)将事件处理程序挂钩。

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

这是因为ObservableCollection只是一个容器,其中的每个项目都必须单独连接。当然,您可以编写自己的扩展类(或扩展方法)来帮助自动执行此操作。

答案 1 :(得分:1)

我认为INotifyPropertyChanged会通知propertychanged事件,但在这里我认为您的收藏已更改。所以你必须提出一个CollectionChanged事件。

我建议您查看thisthis

希望这能帮到你!!!!

答案 2 :(得分: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;
        }
    }
}