找出调用contextmenu的以编程方式生成的对象

时间:2014-10-21 14:55:50

标签: c# winforms contextmenu

在我的程序中,我通过右键单击动态生成标签 - >表格中的新内容:

private Point MouseDownLocation;
private List<Label> labelList=new List<Label>();

private void mainContextMenu_Opening(object sender, CancelEventArgs e)
{
  MouseDownLocation = PointToClient(MousePosition);
}

private void valueToolStripMenuItem_Click(object sender, EventArgs e)
{
  Label label = new Label();
  label.Location = MouseDownLocation;
  label.AutoSize = true;
  label.ContextMenuStrip = valueContextMenu;
  label.Text = "test";
  this.Controls.Add(label);
  labelList.Add(label);
}

接下来,我将valueContextMenu与Button Delete一起使用,我希望能够右键单击这样生成的标签,然后删除。

private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
{
}
问题是,在这个函数(被调用)中,没有办法检索调用菜单的标签,因为sender是contextmenu ..

1 个答案:

答案 0 :(得分:0)

尝试检查ContextMenuStrip的SourceControl属性:

private void deleteToolStripMenuItem_Click(object sender, EventArgs e) {
  Control c = ((ContextMenuStrip)((ToolStripMenuItem)sender).Owner).SourceControl;
  if (c != null) {
    // do something...
  }
}