問題描述
我有一個名為 GameButton
的用戶控件,其中有一個標簽.當我將用戶控件添加到我的表單并為其添加一個單擊事件時,它會在您單擊自定義按鈕的背景而不是標簽中的文本時觸發?如果不在用戶控件代碼中添加一堆點擊事件,我將如何解決這個問題?
UI 框架:winforms
如果我對您的理解正確,您的 GameButton 用戶控件將在單擊時觸發該事件,但在單擊標簽時不會觸發該事件——而您兩者都需要.這是因為標簽(控件)位于背景之上.因此,您還需要使用點擊事件注冊您的標簽.這可以在設計器中手動完成,也可以針對頁面上的每個控件以編程方式完成.
如果您想在 UserControl 中執行每個控件,請將其放入 UserControl 的 OnLoad 事件中,您可以為每個控件使用相同的單擊事件:
foreach (var c in this.Controls)c.Click += new EventHandler(yourEvent_handler_click);public void yourEvent_handler_click(對象發送者,EventArgs e){//無論你想讓你的事件處理程序做什么}
最好的方法是在用戶控件中創建單擊事件處理程序屬性.這樣,每次您向用戶控件添加/刪除點擊事件時,它都會自動將其添加/刪除到用戶控件中的所有控件.
public new event EventHandler Click {添加 {base.Click += 值;foreach(Controls 中的控制控件){control.Click += 值;}}消除 {base.Click -= 值;foreach(Controls 中的控制控件){control.Click -= 值;}}}
這是另一個post:p>
希望這會有所幫助!
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!
這篇關于單擊控件內的文本時,用戶控件單擊事件不起作用?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!