Events convention
-
06-07-2021 - |
Pergunta
I'm making an XNA game and I have a question about the convention for events. I made a menu which has buttons, those buttons have 3 events naimly: onClick, onMouseEnter and onMouseLeave.
Atm my code looks like this :
public static void PlayonClick(Button sender, EventArgs args)
{
}
public static void PlayonMouseEnter(Button sender, EventArgs args)
{
}
public static void PlayonMouseLeave(Button sender, EventArgs args)
{
}
This code will repeat for every button in the menu. Now I think it would be better if had 1 event and eventargs will contain what happend (onClick,onMouseLeave,onMouseEnter)
Note: onMouseEnter and onMouseLeave are acttualy the same for every button. So I'm thinking to subscribe all events to 1 method
So, What is they best way to implement this ?
Solução
Assuming you're attaching your handlers in code:
button.onClick += PlayonEvent;
button.onMouseEnter += PlayonEvent;
button.onMouseLeave += PlayonEvent;
If attaching in XAML, do the same sort of thing, which is simply to say that all of the events are handled by the same handler. Either way, define such a handler like:
public static void PlayonEvent(Button sender, EventArgs args)
{
// do something based on EventArgs, which can give you an idea of what's going on
}