4
這是目前相當重複的操作。我正在尋找一種更乾的方式來處理這個問題,但我發現的每個解決方案都不是更好。問題是如果我想要事件作用於父SearchResultItem。例如,如果標籤位於父控件的邊緣,則父控件從不會看到鼠標離開或進入,如果它發生在該子標籤內部。所以我也是每個孩子的方法。但是,如果有一個孩子加入,我必須記住,併爲每個事件添加它。還會有雙擊和點擊事件。你知道更好的方法嗎?大多數DRY方法將父子事件提升到父級UserControl
這裏是我的代碼,簡化爲只顯示什麼是相關的:
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;
}
}
我編輯了你的標題。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 –