2

我已将一些项目动态添加到我的菜单条中,并为添加到条中的每个项目触发和事件(项目是从 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();
}
4

2 回答 2

4

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

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();
}
于 2012-10-21T21:15:51.990 回答
1

您可以使用Tag属性ToolStripMenuItem来存储有关项目的任何附加数据(例如页面值):

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

Tag 的类型为object,因此您需要在检索值期间对其进行转换:

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

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

string page = clickedItem.Text;
于 2012-10-21T21:14:25.917 回答