問題描述
我有一個(gè)名為 GameButton
的用戶控件,其中有一個(gè)標(biāo)簽.當(dāng)我將用戶控件添加到我的表單并為其添加一個(gè)單擊事件時(shí),它會(huì)在您單擊自定義按鈕的背景而不是標(biāo)簽中的文本時(shí)觸發(fā)?如果不在用戶控件代碼中添加一堆點(diǎn)擊事件,我將如何解決這個(gè)問題?
UI 框架:winforms
如果我對(duì)您的理解正確,您的 GameButton 用戶控件將在單擊時(shí)觸發(fā)該事件,但在單擊標(biāo)簽時(shí)不會(huì)觸發(fā)該事件——而您兩者都需要.這是因?yàn)闃?biāo)簽(控件)位于背景之上.因此,您還需要使用點(diǎn)擊事件注冊(cè)您的標(biāo)簽.這可以在設(shè)計(jì)器中手動(dòng)完成,也可以針對(duì)頁面上的每個(gè)控件以編程方式完成.
如果您想在 UserControl 中執(zhí)行每個(gè)控件,請(qǐng)將其放入 UserControl 的 OnLoad 事件中,您可以為每個(gè)控件使用相同的單擊事件:
foreach (var c in this.Controls)c.Click += new EventHandler(yourEvent_handler_click);public void yourEvent_handler_click(對(duì)象發(fā)送者,EventArgs e){//無論你想讓你的事件處理程序做什么}
最好的方法是在用戶控件中創(chuàng)建單擊事件處理程序?qū)傩?這樣,每次您向用戶控件添加/刪除點(diǎn)擊事件時(shí),它都會(huì)自動(dòng)將其添加/刪除到用戶控件中的所有控件.
public new event EventHandler Click {添加 {base.Click += 值;foreach(Controls 中的控制控件){control.Click += 值;}}消除 {base.Click -= 值;foreach(Controls 中的控制控件){control.Click -= 值;}}}
這是另一個(gè)post:p>
希望這會(huì)有所幫助!
I have a user control called GameButton
that has a label inside it. When I add the user control to my form, and add a click event to it, its triggered when you click on the background of the custom button, but not the text in the label? How would I fix this without adding a bunch of click events inside the user controls code?
edit: UI framework: winforms
If I am understanding you properly, your GameButton usercontrol will fire the event when clicked on, but not when the label is clicked on -- and you want both. This is because the label (a control) is on top of the background. Therefore, you need to register your label with the click event as well. This can be done manually in the designer or programmatically for each control on the page.
If you want to do EVERY control in the UserControl, put this into the UserControl's OnLoad event and you can use the same click event for every control:
foreach (var c in this.Controls)
c.Click += new EventHandler(yourEvent_handler_click);
public void yourEvent_handler_click (object sender, EventArgs e){
//whatever you want your event handler to do
}
EDIT: The best way is to create the click event handler property in the user control. This way, every time you add/remove a click event to your user control, it adds/removes it to all the controls within the user control automatically.
public new event EventHandler Click {
add {
base.Click += value;
foreach (Control control in Controls) {
control.Click += value;
}
}
remove {
base.Click -= value;
foreach (Control control in Controls) {
control.Click -= value;
}
}
}
This is as per another post:
Hope this helps!
這篇關(guān)于單擊控件內(nèi)的文本時(shí),用戶控件單擊事件不起作用?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!