我在Visual Studio中的哪里找到事件声明 [英] Where do I find event declarations in Visual Studio

查看:303
本文介绍了我在Visual Studio中的哪里找到事件声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道VS将通过双击事件来打开事件处理程序存根. 我在按钮所在窗体的InitializeComponent中找到了基础事件声明.

I know that VS will open an eventhandler stub by doubleclicking on an event. I found the underlying event declaration in InitializeComponent of the form on which the button is located.

this.buttonWorkOn.Click += new System.EventHandler(this.buttonWorkOn_Click);

我可以使用此事件声明(Visual Studio的)并向其注册另一个事件处理方法吗?

Can I use this event declaration (of Visual Studio) and register another eventhandling method with it?

在实例化其他表单时,其事件处理方法将需要使用主表单上按钮的click事件进行注册.
即使我已经阅读了很多有关代表和事件的知识,我也不知道如何做到这一点,并且从原则上讲,我确实了解它是如何工作的.

Upon instantiation of that other form its eventhandling method would need to register itself with the click event of the button on the main form.
I have no clue how to do that even though I have read quite a bit about delegates and events and in principle I do understand how it works.

谢谢

推荐答案

如果在代码编辑器中右键单击事件处理程序,然后浏览定义,您将找到声明它的方式,然后可以在您的声明中使用它.自己的代码.

If you right click on an event handler in the code editor and browse the definition you will find the way that it is declared, which you can then use in your own code.

例如,ButtonClick事件的声明为:

For example, the declaration for a Button's Click event is:

    public event EventHandler Click;

您可以自己添加这些内容,并在其他地方使用它们来响应您创建的任何类中的事件.

You can add these yourself and use them from other places to respond to events in any class you create.

这是一个带有一个按钮的示例表单(通过设计器添加),单击该按钮将引发自己的事件:

Here's a sample form with a single button (added via the designer) that when clicked will raise its own event:

public partial class Form1 : Form
{
    public event EventHandler ButtonClicked;

    private void RaiseButtonClicked()
    {
        if (ButtonClicked != null)
            ButtonClicked(this, EventArgs.Empty);
    }

    public Form1()
    {
        InitializeComponent();
    }

    private void Button1_Click(object sender, EventArgs e)
    {
        RaiseButtonClicked();
    }
}

然后在另一个类中,您可以为其添加处理程序:

In another class you can then add a handler to that:

public class Responder
{
    public Responder(Form1 form)
    {
        form.ButtonClicked += OnButtonClicked;
    }

    private void OnButtonClicked(object sender, EventArgs args)
    {
        MessageBox.Show("Button was clicked");
    }
}

现在,Responder类的每个实例都会告诉您何时单击表单上的按钮.

Now every instance of the Responder class will tell you when the button is clicked on the form.

这篇关于我在Visual Studio中的哪里找到事件声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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