简体   繁体   中英

Events preview of child controls on Parent control

Is there a way to fire the child controls event on the parent control?

Sample: a custom user control called ControlA containing other controls, like a PictureBox and a Label. The ControlA is added to a Form and a MouseClick event is set. If the user clicks on the empty areas of the control, the event is fired, but if the user clicks over the child controls, like the PictureBox and the Label, nothing happens. This is because the child controls are over the Background and will handle the events.

The solution that I found is to add that:

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

But I will need to do that to all Events that I want to use, is there some another way to solve that, like setting some property on the child controls, so I don't need to "override" a lot of events?

I had a similar situation. I used this solution but modified it to handled the objects I had. The difference was that I have several different kinds of user component that are composed of a mixed of user components and regular components, but I needed the parent component to handle the DragDrop's related events and this because the parent component had access to all the information needed. I modified this solution to be recursive, (I'm not sure it is the best solution but…) and this save me a tone of work. I can take this and copy and paste it on other components and modify the event handlers to the particular situations. It goes like this:

    private void HookChildrenEvents(Control control)
    {
        foreach (Control child in control.Controls)
        {
            if (child.Controls.Count > 0)
            {
                HookChildrenEvents(child);
            }
            child.DragEnter += child_DragEnter;
            child.MouseHover += child_MouseHover;
            child.MouseDown += child_MouseDown;
            child.DragDrop += child_DragDrop;
            child.AllowDrop = true;
        }
    }

Create a method to wire-up desired events for all children. If needed, a counter-method: UnhookChildEvents can be created.

public void HookChildEvents()
{
    foreach (Control child in this.Controls)
    {
        child.MouseClick += ChildOnMouseClick;
        child.DragEnter += ChildOnDragEnter;
        // ... add one for each event you care for.
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM