将价值传递给事件处理程序



我已经在菜单上添加了一些项目并触发了一些项目,并为添加到条带的每个项目(从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();
}

我建议您使用标签属性。它是对象,因此您需要知道要使用哪种类型来施放它。像这样的东西

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();
}

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

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

标签具有object的类型,因此您需要在检索值期间投射它:

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

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

string page = clickedItem.Text;

相关内容

  • 没有找到相关文章

最新更新