Joel
Joel

Reputation: 7569

Event subscribed using reflection not firing

I have this code:

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

However, AllItems_CollectionChanged method never gets called.

Can anybody can tell me why?


EDIT

I have several Lists, e.g.:

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

and I really want to avoid having to (un)subscribe manually to their CollectionChanged event, and there may be several listeners as well.

Upvotes: 0

Views: 116

Answers (1)

Michael Gunter
Michael Gunter

Reputation: 12811

There's something missing from your question. The following complete program demonstrates that the CollectionChanged event is called.

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

Upvotes: 3

Related Questions