大多数DRY方式将子事件提升到父UserControl

时间:2013-01-04 18:37:23

标签: c# winforms

目前这是非常重复的。我正在寻找一种更干的方式来解决这个问题,但我找到的每个解决方案都没有更好。问题是如果我希望事件作用于父SearchResultItem。例如,如果标签位于父控件的最边缘,则父控件永远不会看到鼠标离开,如果它发生在该子标签内,则输入。所以我也是每个孩子的方法。但是,如果要添加一个孩子,我必须记住并为每个事件添加它。还会有双击和点击事件。你知道更好的方法吗?

这是我的代码,简化为显示相关内容:

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;
    }
}

1 个答案:

答案 0 :(得分:4)

您可以为表单的Controls集合中的每个控件添加此事件处理程序。

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

请注意,如果您需要来自窗体上容器控件内的控件的事件,则可能需要递归。我还假设您没有在运行时动态添加控件。