简体   繁体   English

如何处理 C# 中的菜单项以传递值

[英]How to handle menu items in C# for passing values

I am working in Windows Forms in C#.我在 C# 中的 Windows 窗体中工作。 I have a method where I am adding MenuItem s to the ContextMenu and I implemented the event handlers for the MenuItem s as below:我有一个方法,我将MenuItem s 添加到ContextMenu并且我实现了MenuItem s的事件处理程序,如下所示:

public void Form1_Load()
{
    int index = 0;
    ArrayList ar = new ArrayList();
    ContextMenu cm = new ContextMenu();
    cm.Name = "Test";
    MenuItem mi = new MenuItem("All");
    mi.Click += new EventHandler(mi_All);
}

private void mi_All(object sender, EventArgs e)
{
    // Here I want to access the arraylist and integer specified in above method
}

How can this be done?如何才能做到这一点? One possible solution is to declare the ArrayList and int as global variables, but I have a lot of variables like this.一种可能的解决方案是将ArrayListint声明为全局变量,但我有很多这样的变量。 If I take this approach, the variables will live until the form gets disposed.如果我采用这种方法,变量将一直存在,直到表单被处理。 So this doesn't work.所以这行不通。 Is there another way of achieving this?有没有另一种方法来实现这一目标?

One option:一种选择:

mi.Click += delegate (object sender, EventArgs e) { mi_All(sender, e, ar, index); };
...
private void mi_All(object sender, EventArgs e, ArrayList ar, int index)
{
   ...
}

Another:其他:

mi.Tag = new object[] { ar, index };
...
private void mi_All(object sender, EventArgs e)
{
    ArrayList ar = (ArrayList)((object[])((MenuItem)sender).Tag)[0];
    int index = (int)((object[])((MenuItem)sender).Tag)[1];
    ...
}

The MenuItem has a Tag property that can be used to assign any custom information you like. MenuItem有一个Tag属性,可用于分配您喜欢的任何自定义信息。 So assign to this whatever you need to access when the event handler is invoked.因此,当调用事件处理程序时,将您需要访问的任何内容分配给它。 In your example you would assign the integer index of the enu item and then inside the event handler use that as the index into the Form level ArrayList field.在您的示例中,您将分配 enu 项的整数索引,然后在事件处理程序中将其用作表单级别 ArrayList 字段的索引。

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

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