views:

51

answers:

1

I am creating a class that derives from the WPF RichTextBox control and I need to execute some code in the copy and paste events.

I understand that, whenever possible, it is best practice to implement event-based code in a derived class by overriding the base class method that raises the event. However, no such method exists in this case, so is it acceptable for my derived class to add an event handler to its own base class events?

If I do add an event handler, I assume that it should be explicitly removed when the control is disposed. However, I am not sure how best to do this in the case of RichTextBox as WPF control classes do not seem to have any mechanism for detecting disposal.

Any suggestions please?

Thanks, Tim

+3  A: 

Of course, you can handle events of the base class. It's commonly done for the Loaded event, for instance, since there is no OnLoaded method.

You don't need to worry about removing the handler: since the event publisher and subscriber are the same instance, not removing the handler won't prevent the GC from collecting your object.

Thomas Levesque
@Thomas - many thanks for that clarification. It seems obvious when it's pointed out. Does the same rule apply when applying a handler to a contained object - in the case of RichTextBox I will be handling the events of its contained DataObject instance? Thanks again.
Tim Coulter
You only need to worry about events published by objects that have a longer lifetime than the subscriber. If there are no external references to the DataObject, it will be eligible for garbage collection and won't prevent your control from being collected.
Thomas Levesque