获取对触发change事件的ObservableCollection的引用

时间:2015-02-03 05:24:57

标签: c# .net events observablecollection

的ObservableCollection<>公开CollectionChanged事件。从该事件的处理程序是否有任何方法来获取对触发事件的ObservableCollection的引用?我原以为sender参数是ObservableCollection,但不是。

此代码示例说明10个ObservableCollections都将其CollectionChanged事件注册到一个方法。从那一个方法我想得到改变的ObservableCollection的引用:

internal class Program
{
    private static void Main(string[] args)
    {
        List<ObservableCollection<int>> collections = new List<ObservableCollection<int>>();

        for (int i = 0; i < 10; i++)
        {
            ObservableCollection<int> collection = new ObservableCollection<int>();
            collection.CollectionChanged += CollectionOnCollectionChanged;
            collections.Add(collection);
        }

        collections[5].Add(1234);
    }

    private static void CollectionOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs)
    {
        if (notifyCollectionChangedEventArgs.Action == NotifyCollectionChangedAction.Add)
        {
            // Before proceeding I need to get a reference to the ObservableCollection<int> where the change occured which fired this event.
        }
    }
}

查看传递给事件处理程序的参数,我没有看到对ObservableCollection的引用,所以我假设我无法得到它。

2 个答案:

答案 0 :(得分:1)

sender对象是触发事件的ObservableCollection实例。你可以施展它。

 private static void CollectionOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs)
 {
     if (notifyCollectionChangedEventArgs.Action == NotifyCollectionChangedAction.Add)
     {
         ObservableCollection<int> myCollection = sender as ObservableCollection<int>;
         if(myCollection != null){
             //do whatever you want
         }
     }
 }

答案 1 :(得分:0)

另一个选择是使用内联委托并在集合上形成一个闭包,如下所示:

private static void Main(string[] args)
{
    List<ObservableCollection<int>> collections = new List<ObservableCollection<int>>();

    for (int i = 0; i < 10; i++)
    {
        ObservableCollection<int> collection = new ObservableCollection<int>();
        collection.CollectionChanged += (s, e) =>
        {
            if (e.Action == NotifyCollectionChangedAction.Add)
            {
                // Can reference `collection` directly here
            }
        };
        collections.Add(collection);
    }

    collections[5].Add(1234);
}

来自发件人对象的保存转换(我觉得很乱。)

另一种写这个的方法可能是:

private static void Main(string[] args)
{
    List<ObservableCollection<int>> collections =
        Enumerable
            .Range(0, 10)
            .Select(n => new ObservableCollection<int>())
            .ToList();

    collections
        .ForEach(collection =>
        {
            collection.CollectionChanged += (s, e) =>
            {
                if (e.Action == NotifyCollectionChangedAction.Add)
                {
                    // Can reference `collection` directly here
                }
            };
        });

    collections[5].Add(1234);
}