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