将值传递给事件处理程序

时间:2012-10-21 21:11:49

标签: c# winforms event-handling menustrip

我已动态地向菜单条添加了一些项目,并为添加到条带的每个项目触发了事件(项目从XML文件中添加)。 我接下来要做的是将文本从每个项目传递给事件处理程序,以便我可以在一个线程中使用它们。这有可能吗?有人可以帮我解决一下这个问题吗?

这是我的代码:

private void historyMenuItem_Click(object sender, EventArgs e){
    XmlDocument doc = new XmlDocument();  // create new xml document
    doc.Load("..\\history.xml");  // load the xml
    // create a new node list
    // and select nodes from BookItems/Book
    XmlNodeList nodeList = doc.SelectNodes("URLs/http"); 

    historyMenuItem.DropDownItems.Clear();
    foreach (XmlNode node in nodeList) {
        string page = node.Attributes["page"].Value;
        //http://msdn.microsoft.com/en-us/library/ms160990.aspx
        ToolStripMenuItem windowNewMenu = new ToolStripMenuItem(page, null, new EventHandler(MenuItemClickHandler));
        historyMenuItem.DropDownItems.Add(windowNewMenu);
    }
}

private void MenuItemClickHandler(object sender, EventArgs e){
    ToolStripMenuItem clickedItem = (ToolStripMenuItem)sender;
    ## HERE IS WHERE I NEED HELP:
    UrlTextBox = (I need value of page here!);
    this.thread = new Thread(new ThreadStart(this.httpRequestMultiThread));
    this.thread.Start();
}

2 个答案:

答案 0 :(得分:4)

我建议你使用Tag Property。它是对象,因此您需要知道在要使用它时要将其强制转换为哪种类型。像这样的东西

private void historyMenuItem_Click(object sender, EventArgs e)
    {
        XmlDocument doc = new XmlDocument();  // create new xml document
        doc.Load("..\\history.xml");  // load the xml
        XmlNodeList nodeList = doc.SelectNodes("URLs/http");  // create a new node list
                                                              // and select nodes from BookItems/Book
        historyMenuItem.DropDownItems.Clear();
        foreach (XmlNode node in nodeList)   // for each node in the node list
        {
            string page = node.Attributes["page"].Value;

            ToolStripMenuItem windowNewMenu = new ToolStripMenuItem(page, null, new EventHandler(MenuItemClickHandler));
            windowMenuItem.Tag = page;
            historyMenuItem.DropDownItems.Add(windowNewMenu);
        }
    }
private void MenuItemClickHandler(object sender, EventArgs e)
{
    ToolStripMenuItem clickedItem = (ToolStripMenuItem)sender;

    UrlTextBox.Text = (string)clickedItem.Tag;
    this.thread = new Thread(new ThreadStart(this.httpRequestMultiThread));
    this.thread.Start();
}

答案 1 :(得分:1)

您可以使用ToolStripMenuItem的{​​{3}}属性来存储有关该项目的任何其他数据(例如页面价值):

windowNewMenu.Tag = node.Attributes["page"].Value;

标记的类型为object,因此您需要在检索值期间强制转换它:

ToolStripMenuItem clickedItem = (ToolStripMenuItem)sender;
string page = clickedItem.Tag as string;

但是在您当前的解决方案中,页面的值被分配给菜单项的Text属性(当您创建项目时)。因此,您可以从该属性中检索值:

string page = clickedItem.Text;