最干净的方法将子控件事件传递给父控件UserControl

4

这段代码目前非常重复。我正在寻找一种更DRY的处理方式,但我找到的每个解决方案都不是真正的更好。问题在于,如果我想让事件作用于父级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
我已经编辑了你的标题。请参考“问题的标题应该包含“标签”吗?”,在那里达成共识是“不应该”。 - John Saunders
1个回答

4

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

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

请注意,如果您需要在表单上获取容器控件内控件的事件,则可能需要使用递归功能。我还假设您不会在运行时动态添加控件。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接