ToolStripMenuItem用于多个ContextMenuStrip

时间:2011-11-29 08:48:30

标签: c# .net wpf contextmenu contextmenustrip

我有一个包含多个页面的标签面板的表单。每个都有自己的上下文菜单(右键单击显示)。但是如果我将ToolStripMenuItem添加到多个ContextMenuStrips,则只有最后一个菜单条确实具有此菜单项。 简单的代码示例是:

    ToolStripMenuItem tim_refresh = new ToolStripMenuItem("Refresh", null, (o, e) =>
        {
            MessageBox.Show("Refresh");
        });

    ContextMenuStrip cms1 = new ContextMenuStrip();
    cms1.Items.Add(tim_refresh);

    ContextMenuStrip cms2 = new ContextMenuStrip();
    cms2.Items.Add(tim_refresh);

    this.tblDataManagerObjects.ContextMenuStrip = cms1;
    this.tblDataSourceTypes.ContextMenuStrip = cms2;

如果一个人逐个显示这个菜单,首先是空的......我怎样才能达到我的目的?

2 个答案:

答案 0 :(得分:1)

这是因为视觉不能同时是多个不同视觉的孩子。在您的情况下,tim_refresh同时是cms1cms2的孩子。

您需要创建两个完全独立的ToolStripMenuItem实例。

修改

您可以使用因子方法提取视觉创建,以简化多个对象实例化:

private ToolStripMenuItem CreateToolStripMenuItem(string name)
{
   return new ToolStripMenuItem(name, null, (o, e) =>
        {
            MessageBox.Show(name);
        });
}

// then just call it once per each menu strip
ContextMenuStrip cms1 = new ContextMenuStrip();
cms1.Items.Add(CreateToolStripMenuItem("Refresh"));

ContextMenuStrip cms2 = new ContextMenuStrip();
cms2.Items.Add(CreateToolStripMenuItem("Refresh"));

答案 1 :(得分:1)

一次显示一个上下文菜单;您可能不需要到处都有很多克隆,但是您可能希望在菜单条打开时将菜单项的一个实例移动到菜单菜单条;

当本地副本为空时,我正在将命名(大)父项的项移动到子(当前打开)菜单,并且所有下一个ctx开口我只是AddRange,它移动“定位”三个菜单项先前打开的ctxMenuStrip到当前开放的一个:

    // http://stackoverflow.com/questions/8307959/toolstripmenuitem-for-multiple-contextmenustrip?rq=1
    // http://stackoverflow.com/questions/6275120/toolstripmenuitem-added-to-several-places?rq=1
    // WILL_ADD_PARENT_MENU_ITEMS_IN_Opening first time opened we locate common menu items from GrandParent, then we move them to the current slider; cool?
    private static ToolStripItem[] separatorLoadSave = null;
    private void contextMenuStrip1_Opening(object sender, CancelEventArgs e) {
        if (separatorLoadSave == null) {
            separatorLoadSave = new ToolStripItem[3];

            Control slidersAutoGrow = base.Parent;
            if (base.Parent.Name != "SlidersAutoGrow") return;
            Control slidersForm = slidersAutoGrow.Parent;
            if (slidersForm.Name != "SlidersForm") return;

            ToolStripItem[] separator = slidersForm.ContextMenuStrip.Items.Find("toolStripSeparator1", false);
            if (separator.Length > 0) separatorLoadSave[0] = separator[0];

            ToolStripItem[] load = slidersForm.ContextMenuStrip.Items.Find("mniParameterSetLoad", false);
            if (load.Length > 0) separatorLoadSave[1] = load[0];

            ToolStripItem[] save = slidersForm.ContextMenuStrip.Items.Find("mniParameterSetSave", false);
            if (save.Length > 0) separatorLoadSave[2] = save[0];
        }

        this.contextMenuStrip1.SuspendLayout();
        this.contextMenuStrip1.Items.AddRange(separatorLoadSave);
        this.contextMenuStrip1.ResumeLayout();
    }