Mike Haas
Mike Haas

Reputation: 2553

most DRY way to raise child events to the parent UserControl

This is currently pretty repetitive. I'm looking for a more DRY way to deal with this but each solution I've found is not really any better. The problem is if I want the events to act on the parent SearchResultItem. If a label for example is on the very edge of the parent control, the parent control never sees a mouse leave or enter if it happens inside of that child label. So I'm the method to each child as well. However, if a child is ever added, I have to remember and go and add it for each event I have. There will also be double click and click events. Do you know of a better way of doing this?

Here is my code, simplified to show just what is relevant:

public partial class SearchResultItem : UserControl
{
    public SearchResultItem()
    {
        SetupForm();
    }

    private void SetupForm()
    {
        //Setup the back color change on mouse enter
        SetupMouseEnter();
        //Setup the original back color when mouse leave
        SetupMouseLeave();
    }

    private void SetupMouseLeave()
    {
        this.MouseLeave += SearchResultItem_MouseLeave;
        this.lblRight.MouseLeave += SearchResultItem_MouseLeave;
        this.lblBottom.MouseLeave += SearchResultItem_MouseLeave;
        this.lblColor.MouseLeave += SearchResultItem_MouseLeave;
        this.lblTop.MouseLeave += SearchResultItem_MouseLeave;
        this.picture.MouseLeave += SearchResultItem_MouseLeave;
    }

    void SearchResultItem_MouseLeave(object sender, EventArgs e)
    {
        this.BackColor = Color.FromKnownColor(KnownColor.Control);
    }

    private void SetupMouseEnter()
    {
        this.MouseEnter += SearchResultItem_MouseEnter;
        this.lblRight.MouseEnter += SearchResultItem_MouseEnter;
        this.lblBottom.MouseEnter += SearchResultItem_MouseEnter;
        this.lblColor.MouseEnter += SearchResultItem_MouseEnter;
        this.lblTop.MouseEnter += SearchResultItem_MouseEnter;
        this.picture.MouseEnter += SearchResultItem_MouseEnter;
    }

    void SearchResultItem_MouseEnter(object sender, EventArgs e)
    {
        this.BackColor = Color.BlanchedAlmond;
    }
}

Upvotes: 4

Views: 509

Answers (1)

user27414
user27414

Reputation:

You can add this event handler for every control in the form's Controls collection.

foreach (Control c in this.Controls)
{
    c.MouseLeave += SearchResultItem_MouseLeave;
}

Note that if you may need this to be recursive if you need events from controls inside container controls on the form. I'm also assuming that you're not adding controls dynamically at runtime.

Upvotes: 4

Related Questions