简体   繁体   English

声明并初始化带有事件处理程序的ToolStripMenuItem

[英]Declare and Initialize a ToolStripMenuItem with an Event Handler

I have a ToolStripMenuItem that I want to declare and instantiate with a String, a null value for an image, and an Event Handler for its Click event. 我有一个ToolStripMenuItem,我想用一个String声明和实例化,一个图像的null值,及其Click事件的事件处理程序。 This is the format Intellisense is expecting: 这是Intellisense期望的格式:

ToolStripMenuItem(string text, System.Drawing.Image image, EventHandler onClick).

But I am unable to assign the Event Handler and I do not know the proper syntax to do so. 但是我无法分配事件处理程序,并且我不知道这样做的正确语法。 As a workaround, I assign the .Click event in the constructor like so... 解决方法是,在构造器中分配.Click事件,如下所示:

class Timer
{
    //The other WinForms objects and my methods are omitted.
    private ToolStripMenuItem StartButton = new ToolStripMenuItem("Start Timer");

    public Timer()
    {
        //I want the assignment of StartButton_Click in my declaration and initialization of StartButton, not here.
        StartButton.Click += new EventHandler(StartButton_Click);
    }

    public void StartButton_Click(object sender, EventArgs e)
    {
        //The logic here is not relevant.
    }
}

I tried the syntax below but I keep getting the error: "CS0236 A field initializer cannot reference the non-static field, method, or property 'Timer.StartButton_Click(object, EventArgs)'" 我尝试了以下语法,但始终收到错误消息:“ CS0236字段初始化程序无法引用非静态字段,方法或属性'Timer.StartButton_Click(object,EventArgs)'”

new ToolStripMenuItem("Start Timer", null, new EventHandler(StartButton_Click));

Intelliense suggests I use the format Intelliense建议我使用格式

EventHandler(void(object,EventArgs)target)

but I do not know how to fill out the expected syntax property. 但我不知道如何填写预期的语法属性。 How do I write the declaration of StartButton so that the method StartButton_Click is called after a Click event? 如何编写StartButton的声明,以便在Click事件之后调用StartButton_Click方法?

The correct place to instantiate it is in the constructor. 实例化它的正确位置是在构造函数中。 Do it all at once, like this: 一次完成所有操作,就像这样:

private ToolStripMenuItem StartButton;

public Timer()
{
    StartButton = new ToolStripMenuItem("Start Timer", null, StartButton_Click);
}

As for that compiler error, you can read more about it here , although it's sparse on the details. 至于该编译器错误,尽管细节很少,您可以在这里阅读更多信息。

From Stack Overflow : You cannot use an instance variable to initialize another instance variable. 来自堆栈溢出 :您不能使用实例变量来初始化另一个实例变量。 Why? 为什么? Because the compiler can rearrange these - there is no guarantee that reminder will be initialized before StartButton_Click, so the above line might throw a NullReferenceException. 由于编译器可以重新排列这些内容-无法保证在StartButton_Click之前会初始化提醒,因此上一行可能会抛出NullReferenceException。

Make the method static and you should be good to go. 将方法设为静态,应该会做得很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM