.Net(Windows 窗体)用户控件的单击事件
这可能是一个非常简单的问题,但出于某种原因,即使是网络搜索答案的正确方法也让我困惑......
我正在尝试创建一个由一些标签和进度条组成的用户控件。但是,我希望整个控件都有一个“Click”事件,无论单击控件内的哪个项目,都会引发该事件。我创建了一个分配给每个控件的“HandleClick”过程:
private void HandleClick(object sender, EventArgs e)
{
// Call the callback function, if we were asked to
if (OnClick != null)
{
EventArgs ee = new EventArgs();
OnClick(this, ee);
}
else
{
MessageBox.Show("OnClick was null!");
}
}
此实例中的 OnClick 是在控件级别定义的变量:
public new event EventHandler OnClick;
现在,这只在表单上正常工作。它在一个标签上显示 MessageBox,然后调用封闭表单上的事件。其余的都显示消息框。
我觉得这应该是显而易见的,但是一个下午的挫败感让我觉得我错过了一些本应不言而喻的东西,但当我看到它时,我会觉得自己像个彻头彻尾的小丑……任何人都可以吗?不要再对我的愚蠢咯咯笑了足够长的时间来启发我哪里错了?
This is probably a very simple question, but for some reason, even the right way to web search for the answer eludes me...
I'm trying to create a user control that consists of a few labels and progress bars. However, I want the entire control to have a "Click" event that is raised no matter what item inside the control is clicked on. I've created a "HandleClick" procedure that is assigned to each control:
private void HandleClick(object sender, EventArgs e)
{
// Call the callback function, if we were asked to
if (OnClick != null)
{
EventArgs ee = new EventArgs();
OnClick(this, ee);
}
else
{
MessageBox.Show("OnClick was null!");
}
}
OnClick in this instance is a variable defined at control level:
public new event EventHandler OnClick;
Now, this only works properly on the form. On one label it shows the MessageBox, and then calls the event on the enclosing form. All the rest show the message box.
I get the feeling that this should be obvious, but an afternoon of frustration has left me feeling I'm missing something that should be self-evident, but when I see it I am going to feel like a complete buffoon... can anyone stop giggling at my daftness long enough to enlighten me where I've gone wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对此感到抱歉 - 只是给出一个答案,以防有人用谷歌搜索它...
如果您有兴趣,这篇文章帮助解决了这个问题:用户Control Click - Windows Forms… 基本上,删除 HandleClick 和属性并替换为这个:
Sorry about this - just putting an answer on in case someone googles it...
In case you're interested, this post helped solve it: User Control Click - Windows Forms… Basically, remove HandleClick, and the property and substitute this one instead:
我从未在 Windows 窗体中尝试过此操作,但在其他 GUI 中,我放置了一个覆盖整个窗体的透明面板,这样当您单击“窗体上”时,事件实际上会转到面板控件。
I've never tried this with Windows Forms, but in other GUIs I've placed a transparent panel that covers the entire form so that when you click "on the form," the event actually goes to the panel control.