Is it possible to disable context menu items based

2019-04-09 23:50发布

I will have some sort of nodes for a treeview as follows

Root |-> some.txt(A text file which was added at runtime) |->Child(child for some.txt) |-> child1(child for child)

I designed my context menu with some options as New and Remove

What i need is when i righclick on Root, child or child i would like to disable the Remove option

2条回答
戒情不戒烟
2楼-- · 2019-04-09 23:57
// Remove all the Empty sub menu items
int counter = MainMenu.Items[1].ChildItems.Count;
for(int i=0; i<counter;i++)
{
    foreach (MenuItem item in MainMenu.Items[1].ChildItems)
    {
        if (item.ChildItems.Count != 0)
            continue;
        MainMenu.Items[1].ChildItems.Remove(item);
        break;
    }
}
查看更多
ら.Afraid
3楼-- · 2019-04-10 00:07

For a ContextMenu, you can handle the ContextMenu.Popup event and enable/disable menu options before the menu is shown.

For a ContextMenuStrip, you can do the same using the Opening event.

For example, if you use the Menu item Tag property to determine if remove is supported (This is just for the example). You can do some thing like this

private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{
  if ((int)treeView1.SelectedNode.Tag == 1)
  {
    removeToolStripMenuItem.Enabled = true;
  }
  else
  {
    removeToolStripMenuItem.Enabled = false;
  }
}
查看更多
登录 后发表回答