Panels with items acting like a button

2019-09-15 09:50发布

问题:

I have some Panel's and each Panel has a PictureBox and a Label in it.

public static void redPanel(Panel panel1)
{
   panel1.MouseEnter += new EventHandler((o, a) => panel1.BackColor = Color.Brown);
   panel1.MouseDown += new MouseEventHandler((o, a) => panel1.BackColor = Color.DarkRed);
   panel1.MouseUp += new MouseEventHandler((o, a) => panel1.BackColor = Color.Firebrick);
   panel1.MouseLeave += new EventHandler((o, a) => panel1.BackColor = Color.Firebrick);
}

I made this code so the panel reacts to mouse hover and click ... but if I hover the Label or the PictureBox the Panel reverts to its original color. I want that the Label and the PictureBox to act exactly like the Panel (ex: If I click the Label I want that to count as a click on the Panel).

I want some code ... like SourceControl or something for the function from top to manage its own Label and PicureBox.

P.S: I tried to make another functions for Label and PictureBox but each Panel has different color so It means that I need to have about 23 lines of code just for labels ...

回答1:

Quick answer: just attach the same handler to all of them.

public static void redPanel(Panel panel1)
{
    var mouseEnter = new EventHandler((o, a) => panel1.BackColor = Color.Brown);
    panel1.MouseEnter += mouseEnter;
    pictureBox1.MouseEnter += mouseEnter;
    label1.MouseEnter += mouseEnter;

    // And so on
}

Better answer: change your code, if it's a reusable component you'd better to create a UserControl with a PictureBox and a Label. From Designer then assign the same event handler to events generated from both of them (plus UserControl itself).

That said a button is much more than that (it has to react to keyboard events, can be focused, can be default button and so on). I'd prefer to derive from button to just add drawing features (a label and an image are very little code).