User control click event not working when clicking on text inside control?

前端 未结 3 712
逝去的感伤
逝去的感伤 2020-12-19 07:23

I have a user control called GameButton that has a label inside it. When I add the user control to my form, and add a click event to it, its triggered when you

相关标签:
3条回答
  • 2020-12-19 07:57

    You can create a new method and assign all the controls to it

    private void Control_Click(object sender, EventArgs e)
    {
       this.OnClick(e);
    }
    

    This will raise main control(or usercontrol) event.

    0 讨论(0)
  • 2020-12-19 07:59

    If I am understanding you properly, your GameButton usercontrol will fire the event when clicked on, but not when the label is clicked on -- and you want both. This is because the label (a control) is on top of the background. Therefore, you need to register your label with the click event as well. This can be done manually in the designer or programmatically for each control on the page.

    If you want to do EVERY control in the UserControl, put this into the UserControl's OnLoad event and you can use the same click event for every control:

    foreach (var c in this.Controls)
        c.Click += new EventHandler(yourEvent_handler_click);
    
    public void yourEvent_handler_click (object sender, EventArgs e){
        //whatever you want your event handler to do
    }
    

    EDIT: The best way is to create the click event handler property in the user control. This way, every time you add/remove a click event to your user control, it adds/removes it to all the controls within the user control automatically.

    public new event EventHandler Click {
            add {
                base.Click += value;
                foreach (Control control in Controls) {
                    control.Click += value;
                }
            }
            remove {
                base.Click -= value;
                foreach (Control control in Controls) {
                    control.Click -= value;
                }
            }
        }
    

    This is as per another post:

    Hope this helps!

    0 讨论(0)
  • 2020-12-19 08:04

    Set the "enable" property of your labels "False, then mouse events will work in user control.

    0 讨论(0)
提交回复
热议问题