4

目前这是相当重复的。我正在寻找一种更干燥的方法来处理这个问题,但我发现的每个解决方案并没有更好。问题是我是否希望事件作用于父 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;
    }
}
4

1 回答 1

4

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

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.

于 2013-01-04T18:40:44.333 回答