0

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 ?

Svexo
  • 523
  • 1
  • 4
  • 15
  • Do you intend for the _content_ of those events to be the same? That is, the `Click`, `MouseEnter`, and `MouseLeave` actions _all_ do the same thing (say, they all initiate the start of the game). In this case, you can (and should) map them to the same function. If they are doing different things and you intend in your event method to have `if (IsPlayClick) { //do play } elseif (IsPlayMouseEnter) { //highlight button } elseif (IsPlayMouseLeave) { //remove highlight on button }` then you _should_ map them to separate (well named) methods and let each method do one thing and one thing only. – Chris Sinclair Oct 09 '12 at 16:47
  • @ChrisSinclair Yes MouseEnter and MouseLeave will do the same. – Svexo Oct 09 '12 at 16:49
  • 1
    If MouseEnter/MouseLeave have the same code, then I suggest considering mapping them to the same event (as Tim S. showed) and having the `click` map to a separate event handler. Also considering naming the event handler methods something that matches the intended action. For example: `button.MouseEnter += UpdatePlayButtonHighlight;` `button.MouseLeave += UpdatePlayButtonHighlight;` and `button.Click += StartGame;` – Chris Sinclair Oct 09 '12 at 16:55

1 Answers1

0

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
}
Tim S.
  • 55,448
  • 7
  • 96
  • 122
  • I'm attaching them in code, but I wonder if it would be better to have PlayButtonEvent(Button Sender,ButtonState state) and state could be MouseOver, Click or MouseLeave – Svexo Oct 09 '12 at 16:47