.Net(Windows 窗体)用户控件的单击事件 [英] Click event for .Net (Windows Forms) user control

查看:28
本文介绍了.Net(Windows 窗体)用户控件的单击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个非常简单的问题,但出于某种原因,即使是正确的网络搜索方式也让我望而却步......

This is probably a very simple question, but for some reason, even the right way to web search for the answer eludes me...

我正在尝试创建一个由几个标签和进度条组成的用户控件.但是,我希望整个控件都有一个Click"事件,无论单击控件内的什么项目都会引发该事件.我创建了一个分配给每个控件的HandleClick"过程:

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 是在控制级别定义的变量:

OnClick in this instance is a variable defined at control level:

    public new event EventHandler OnClick;

现在,这只能在表单上正常工作.在一个标签上,它显示了 MessageBox,然后在封闭的窗体上调用该事件.其余的都显示消息框.

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?

推荐答案

很抱歉 - 只是提供一个答案,以防有人用谷歌搜索它......

Sorry about this - just putting an answer on in case someone googles it...

如果您有兴趣,这篇文章有助于解决它:用户控制点击 - Windows 窗体...基本上,删除 HandleClick, 和属性并用这个代替:

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:

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;
        }
    }
}

这篇关于.Net(Windows 窗体)用户控件的单击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆