You should make sure the sender and event arguments use a good standard when you raise an event! Use the correct sender and supply good event arguments.
I just got stumped the other day about the sender of an event from a third party control. Doesn’t matter what control. What does matter is the fact that I had to dig around unnecessarily long to figure out how the event parameters worked since they did not work as expected.
The control I used encapsulated a text label, a textbox and a collection of buttons. The control also had an event for ButtonClick. It did one thing good and one thing less good when it came to the parameters used to invoke the ButtonClick event.
To begin with the negative I had an issue with the event sender of the ButtonClick event. The sender was not the control even though the event was defined on the control. Insted the sender was some kind of internal wrapper around some hidden internal container that contained part of the internal logic inside the control. This to me is a huge mistake since most event handlers, myself included, would expect the sender to be the very same control that declared the event.
Here is my very own guidance advice:
DO set the sender of an event to the instanced of the class declaring the event.
Remember I said there was a button collection on the control. You could configure each button the way you liked. More specifically I could set the .Tag property to something useful so that I may tell one button from the next when the click event just said ‘there was a button clicked’. The good call here was that the event arguments of the event were of the custom type ButtonEventArgs that I could use to extract the button clicked via a Button property. All I had to do was say (ButtonEventArgs) args.Button.Tag to get the info I needed on which button was clicked inside the control. Very sweet!
Just to be sure, while I’m on about events; everyone out there is using the generic EventHandler right? Jean-Paul S. Boodhoo was one of the first hits when I just searched for info on this issue: Leveraging the EventHandler<T> delegate more effectively. Rather than me repeating the same explanation; just go ahead and read his. The best type of event declarations look something along the lines of this:
EventHandler<EventArgs<Person>> PersonSelected;
Where my faked PersonSelected event here has a generic EventHandler declaration that takes generic EventArgs for parameter. This means there is no need to box and unbox types sent over this interface.
Cheers,
Magnus
posted @ Wednesday, October 15, 2008 12:00 AM