获取对触发更改事件的 ObservableCollection 的引用

Get a reference to the ObservableCollection that fired the change event

ObservableCollection<> 公开 CollectionChanged 事件。从该事件的处理程序中,是否有任何方法可以获取对触发该事件的 ObservableCollection 的引用?我本以为发件人参数是 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 的引用,所以我假设我无法获取它。

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
         }
     }
 }

您的另一个选择是使用内联委托并像这样在集合上形成闭包:

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);
}