简体   繁体   中英

Elegant way to remove a ToolStripMenuItem

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:

  • having the menu items references property accessors set to internal, or public.
  • On the other hand, I would hide menu items instead of removing them. This can be done in the 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM