I'm using a class derived from UIElement
class when writing a UWP program using C#, where I want to include handling input controls such as mouse and keyboard actions. Now I see there are already virtual methods that says OnSomeEvent()
and clearly I can override these method to fit my handling process, or I can create new method handling the public events defined in the base class, and subscribe them to these input events in the constructor. I assume these two methods both work but I hope to know which is more professional or more advisable way of doing this, and why. Also it would help to explain why MS offers these two ways at the same time.
Here's the events and methods of UIElement
class
https://msdn.microsoft.com/en-us/library/system.windows.uielement(v=vs.110).aspx#Examples
and a paragraph of quoting
UIElement provides a starting point for element layout characteristics, and also exposes virtual methods that derived classes can override, which can influence the layout rendering behavior of the element and its child elements. Much of the input and focusing behavior for elements in general is also defined in the UIElement class. This includes the events for keyboard, mouse and stylus input, and related status properties. Many of these events are routed events, and many of the input-related events have both a bubbling routing version as well as a tunneling version of the event. These paired events are typically the events of greatest interest to control authors.
In a derived class, I usually override the existing method.
Why? Event handler are less reliable than the override method. For example, external classes can clear event handlers, but they can't change the code in the override. You have to seal your own class though, or your method may be overridden.
Another point to consider is this: do I want to change the way the control works? Do I have to have control over the exact execution moment of the code (let's say before the code of the base class, after, or instead of)? If so, you have to use override.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With