dimanche 25 novembre 2018

Unsunscribing from, or checking for, the CollectionChanged event via reflection

I have used reflection in my project to add events to ObservableCollections - specifically, 'CollectionChanged'. I am able to add the event well enough and there is no problem there. The problem is that the code to add the event is run more than once and so I end up with multiple identical events added in some cases. What I don't know how to do is either check to see if there is already an event assigned, or to remove before I add one (to ensure there is only one event added).

The code is here:

foreach (PropertyInfo propertyInfo in props)
        {
            nType = this.GetPropertyInfoTypeObs(propertyInfo.PropertyType);

            if (nType == Static_Enums.TypeEnums.TYPE_OBSERVABLE_COLLECTION)
            {
                var genargs = propertyInfo.PropertyType.GetGenericArguments();

                var o = propertyInfo.GetValue(this, null);

                EventInfo evi = o.GetType().GetEvent("CollectionChanged", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                var eventHandler = new Action<object, NotifyCollectionChangedEventArgs>(
                    (s, a) =>
                    {
                        // Event code here
                        this.MakePropertyDirty(propertyInfo.Name);

                    });

                var del = Delegate.CreateDelegate(evi.EventHandlerType, eventHandler.Target, eventHandler.Method);

                evi.AddEventHandler(o, del);

            }

        }

As stated, this part works fine. But how to handle the issue of the event being added more than once?

I first tried simply having 'evi.RemoveEventHandler(o, del)' on the line above. This doesn't work for me - as in, if I watch what happens when that line is executed, the event handler seems to remain untouched. Perhaps I'm doing it incorrectly?

I'd also be happy with a way to check if the event handler already has one assigned, and then skip over adding it again. But how to do that I've no idea.





Aucun commentaire:

Enregistrer un commentaire