I have a class UserControl class (says MyDataGrid) which inherits from a 3rd party DataGrid (says TheirDataGrid). In this case, I only create MyDataGrid control, but there is no MyDataGridColumn and MyDataGridCell which inherit from TheirDataGridColumn and TheirDataGridCell
My case is that I create some extension method for the TheirDataGridColumn, which will add some event handler to TheirDataGridColumn (by += operator)
If we call the extension method once only, it is fine But if we call the extension method more than one times, the number of events will add up. (In my case, it is still ok, because it only modifies a primitive property in the event and the last event will take effective finally. But still want to know if there is any better way to do so).
There are several approaches I can think of at the moment:
Clearing all the event handler at TheirDataGridColumn each time I call the extension method. But it seems that we can only do it by reflection to retrieve nonpublic variable (How to remove all event handlers from an event). Also, in the case above, it is a well-known default Win Button Control, but I am using a 3rd party one.
Have my own MyDataGridColumn class, which inherits from TheirDataGridColumn, with an extra variable to store added event handle. So, everytime I call the extension function (indeed, at this case, no extension function is needed as we can add the function directly at MyDataGridColumn class), it can remove the event handler (by -= handler).
Have somewhere to store the added event handler so that it can be removed later. But since I am at the extension method, there is no way for me to save the added event handler because there is no extension property. If I save it in static level of another class, it is in static level but not instance level. Sure, I may have a Dictionary at static level, but need to think of a unique key to identify each column.
For 1, it is quite dirty way to do so. Also, it may remove some other event handlers unintentionally
For 2, it needs quite much refactoring, which I would like to avoid
For 3, personally speaking, I prefer this approach, provided I can find a way to save the added event handler and remove it next time when I call this method again
Any help is highly appreciated.