单击控件内的文本时

单击控件内的文本时

本文介绍了单击控件内的文本时,用户控件单击事件不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 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!

这篇关于单击控件内的文本时,用户控件单击事件不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 08:57