I am looking for an elegant way to remove a specific menu item called Annotate
from the ContextMenu
. This is how it is done, so I would appreciate your input on this.
public sealed class ContextMenuStripEx : ContextMenuStrip
{
private readonly ToolStripMenuItem _createAnnotationToolStripMenuItem = new ToolStripMenuItem();
...
public PlotContextMenuStripEx()
{
...
Items.AddRange(new ToolStripItem[]
{
...
_createAnnotationToolStripMenuItem,
...
});
//
// createAnnotationToolStripMenuItem
//
_createAnnotationToolStripMenuItem.Name = "createAnnotationToolStripMenuItem";
_createAnnotationToolStripMenuItem.Size = new Size(169, 22);
_createAnnotationToolStripMenuItem.Image = CommonRes.tsAnnotateM;
_createAnnotationToolStripMenuItem.Text = "Annotate";
}
}
Now imagine somewhere else in another class there is a call to get the ContextMenuStrip, something like:
ContextMenuStrip menuplot = myControl.GetPaneContextMenu();
I want to make the removal part more elegant, because I dont want to rely on the string comparison. Its very ugly:
foreach (var item in menuplot.Items)
{
var name = (item as ToolStripItem).Name;
if (string.Compare(name, "createAnnotationToolStripMenuItem") == 0)
{
// remove the item
}
}
Is there any better way to do this please? many thanks.
I suggest:
Opening
event. The reason is that removing items from the collection may be painful to handle later when the same instance of the context menu is reused.Instead of a loop and removal, I use this way:
void menuplot_Opening(object sender, CancelEventArgs e)
{
...
// Accessible menu items are easier to handle
menuplot.createAnnotationToolStripMenuItem.Visible = false;
...
}
The Opening event is interesting. For example, it allows you to check and cancel the opening of the popup if your conditions are not met by setting e.Cancel = true;