0

我有这个代码:

var listProperty = typeof(WebserviceUtil).GetProperty("List" + typeof(T).Name);
var mainList = (ObservableCollection<T>)listProperty.
    GetValue(WebserviceUtil.Instance, null);
mainList.CollectionChanged += new NotifyCollectionChangedEventHandler(
    AllItems_CollectionChanged);

但是,AllItems_CollectionChanged方法永远不会被调用。

谁能告诉我为什么?


编辑

我有几个列表,例如:

public ObservableCollection<Banana> ListBanana { get; private set; }
public ObservableCollection<Book> ListBook { get; private set; }
// ...
public ObservableCollection<Officer> ListOfficer { get; private set; }

真的很想避免手动(取消)订阅他们的CollectionChanged事件,并且可能还有几个听众。

4

1 回答 1

3

你的问题中缺少一些东西。下面的完整程序演示了调用 CollectionChanged 事件。

using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Diagnostics;

namespace ScratchConsole
{
    static class Program
    {
        private static void Main(string[] args)
        {
            Test<int>();
        }

        private static void Test<T>()
        {
            var listProperty = typeof(WebserviceUtil).GetProperty("List" + typeof(T).Name);
            var mainList = (ObservableCollection<T>)listProperty.GetValue(WebserviceUtil.Instance, null);
            mainList.CollectionChanged += AllItems_CollectionChanged;
            mainList.Add(default(T));
        }

        private static void AllItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            Debug.WriteLine("AllItems_CollectionChanged was called!");
        }

        private class WebserviceUtil
        {
            public static readonly WebserviceUtil Instance = new WebserviceUtil();
            private WebserviceUtil() { ListInt32 = new ObservableCollection<int>(); }
            public ObservableCollection<int> ListInt32 { get; private set; }
        }
    }
}
于 2013-06-14T15:28:53.730 回答