我读过SO几篇文章:
如何借以了解物质引起的ContextMenuStrip控制 获取上下文菜单的控制
并建议使用SourceControl属性的一对夫妇的人..但在这方面没有工作:
我有一个有孩子ToolStripMenuItem一个的ContextMenuStrip - 从Windows窗体设计器生成的段这样的代码:
// _tileContextMenuStrip
//
this._tileContextMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tileKindToolStripMenuItem,
this.forceWidthScalingToolStripMenuItem,
this.forceHeightScalingToolStripMenuItem});
this._tileContextMenuStrip.Name = "_tileContextMenuStrip";
this._tileContextMenuStrip.Size = new System.Drawing.Size(184, 70);
//
// tileKindToolStripMenuItem
//
this.tileKindToolStripMenuItem.Name = "tileKindToolStripMenuItem";
this.tileKindToolStripMenuItem.Size = new System.Drawing.Size(183, 22);
this.tileKindToolStripMenuItem.Text = "Tile Kind";
所以右键菜单条和菜单项列表中的第固定在设计时。 在运行时,TSMI中添加了基于枚举循环孩子TSMIs:
foreach(TileKind t in typeof(TileKind).GetEnumValues()) {
ToolStripMenuItem tsmi = new ToolStripMenuItem(t.ToString("g"));
tsmi.Tag = t;
tsmi.Click += tsmi_Click;
tileKindToolStripMenuItem.DropDownItems.Add(tsmi);
}
后来我有我的表格上20个复选框,我设置其.ContextMenuStrip是同一件事:
foreach(Thing t in someDataSource){
CheckBox c = new CheckBox();
c.Text = t.SomeData;
c.ContextMenuStrip = this._tileContextMenuStrip;
myPanelBlah.Controls.Add(c);
}
太好了,所以现在我有我所有的复选框,它们都显示上下文菜单,当我右键点击他们,但是当我选择一个子菜单项,我只是不能找出发射的上下文菜单控制...
//this the click handler for all the menu items dynamically added
void tsmi_Click(object sender, EventArgs e)
{
ToolStripMenuItem tsmi = sender as ToolStripMenuItem;
(tsmi.OwnerItem //the parent node in the menu tree hierarchy
.Owner as ContextMenuStrip) //it's a ContextMenuStrip so the cast succeeds
.SourceControl //it's always null :(
}
我可以可靠地得到阿霍德的的ContextMenuStrip无论是通过从事件处理程序发送路由了,甚至只是通过引用的ContextMenuStrip本身作为一种形式的实例变量,但SourceControl总是空
任何想法试下呢?