最近碰到个问题,一个MenuItem Add到一个Menu后就会自动去除前一个menu中的引用。因为在Add Menuitem的过程中会调用SetOwner内部函数
internal void SetOwner(ToolStrip newOwner)
{
if (this.owner != newOwner)
{
Font font = this.Font;
this.owner = newOwner;
if (newOwner == null)
{
this.ParentInternal = null;
}
if (!this.state[stateDisposing] && !this.IsDisposed)
{
this.OnOwnerChanged(EventArgs.Empty);
if (font != this.Font)
{
this.OnFontChanged(EventArgs.Empty);
}
}
}
}
如果要在一个程序中几个menu用到很多同样的MenuItem怎么办呢?
一个方法是Clone每一个MenuItem,然后Add到Menu中。
另外一个方法就是利用Menu的opeing和closing事件来达到共享同一MenuItem的目的
初始化MenuItem
this.MenuItem1= new ToolStripMenuItem();
this.MenuItem2= new ToolStripMenuItem();
this.ContextMenu1 = new ContextMenuStrip();
this.ContextMenu2 = new ContextMenuStrip();
this.ContextMenu1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.MenuItem1,
this.MenuItem2
});
挂上事件
this.ContextMenu2.Opening += new CancelEventHandler(this.ContextMenu2_Opening);
this.ContextMenu2.Closing += new ToolStripDropDownClosingEventHandler(this.ContextMenu2_Closing);
动态加载菜单
private void ContextMenu2_Opening(object sender, CancelEventArgs e)
{
this.ContextMenu2.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.MenuItem1,
this.MenuItem2
});
}
private void ContextMenu2_Closing(object sender, ToolStripDropDownClosingEventArgs e)
{
this.ContextMenu1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.MenuItem1,
this.MenuItem2
});
}
这里只是简单演示了MenuItem的共享方法,灵活使用这个方法基本可以解决多个MenuItem在Menu中的共享问题
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/12639172/viewspace-608034/
,如需转载,请注明出处,否则将追究法律责任。