开发者

Should a derived class handle the events of a base class? (C# / WPF)

开发者 https://www.devze.com 2023-01-11 15:58 出处:网络
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 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 cl开发者_StackOverflow中文版asses do not seem to have any mechanism for detecting disposal.

Any suggestions please?

Thanks, Tim


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消