将ToolStripItem添加到ContextMenuStrip中

问题描述 投票:1回答:1

所以这是我的问题。我希望我的上下文菜单打开ToolStrip。我已成功但上下文菜单只会在SECOND右键单击后打开。

我创建了一个显示问题的简单表单。它包含带有一些toolStripMenuItems的menuStrip,一个空的contextMenuStrip和一个用于测试右键单击的按钮。所有这些都是由visual studio设计师创建的。现在这里是相关代码:

namespace Projet_test
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent(); //Contain this line: this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
    }

    //called by the Opening evenHandler of the context menu.
    private void contextOpening(object sender, CancelEventArgs e)
    {
      int j = 0;
      int total = menu1ToolStripMenuItem.DropDownItems.Count;
      for (int i = 0; i < total; i++)
      {
        contextMenuStrip1.Items.Insert(j, menu1ToolStripMenuItem.DropDownItems[0]);
        j++;
      }
    }

    //called by the Closed evenHandler of the context menu.
    private void contextClosed(object sender, ToolStripDropDownClosedEventArgs e)
    {
      int j = 0;
      int total = contextMenuStrip1.Items.Count;
      for (int i = 0; i < total; i++)
      {
        menu1ToolStripMenuItem.DropDownItems.Insert(j, contextMenuStrip1.Items[0]);
        j++;
      }
    }
  }
}

如您所见,右键单击该按钮将显示具有正确ToolStripMenuItems的上下文菜单,但仅在第二次单击后显示..(并在第一次单击时清空menuStrip,因为toolStripMenuItem不能同时位于两个位置)。

然后关闭上下文菜单将正确地重新创建menuStrip。

我不明白,因为在动态添加上下文菜单项时,上下文菜单本身在Form加载时初始化。

那么如何在第一次右键单击时打开上下文菜单?

c# winforms contextmenustrip
1个回答
2
投票

您的ContextMenuStrip为空,这就是它没有显示任何内容的原因。尝试添加“虚拟”项以触发菜单显示自己:

public Form1()
{
  InitializeComponent();
  contextMenuStrip1.Items.Add("dummy");
}

然后在添加新项目之前将其删除:

private void contextMenuStrip1_Opening(object sender, CancelEventArgs e) {
  contextMenuStrip1.Items[0].Dispose();
  int j = 0;
  int total = menu1ToolStripMenuItem.DropDownItems.Count;
  for (int i = 0; i < total; i++) {
    contextMenuStrip1.Items.Insert(j, enu1ToolStripMenuItem.DropDownItems[0]);
    j++;
  }      
}

并在关闭它时再次将其重新添加,以便菜单不再为空:

private void contextMenuStrip1_Closed(object sender, ToolStripDropDownClosedEventArgs e) {
  int j = 0;
  int total = contextMenuStrip1.Items.Count;
  for (int i = 0; i < total; i++) {
    menu1ToolStripMenuItem.DropDownItems.Insert(j, contextMenuStrip1.Items[0]);
    j++;
  }
  contextMenuStrip1.Items.Add("dummy");
}
© www.soinside.com 2019 - 2024. All rights reserved.