ToolStripItems: how to duplicate?

In my scenario, I have a context menu which should show additional sub-menus from loaded plugins.

As I want to use the visual designer (not create the menus each time in code), my problem is how to copy some ToolStripItems from a ToolStrip menu to another. What's happening on simple copy (enumerating in first menu and adding to second) is that the items are removed from the source menu on copy (I assume the Owner changes so the item is automatically removed from the source owner).

ex:
ctxMenuDestination.Items.AddRange(ctxMenuSource.Items)
does not work, as copying removes them from the source collection and gives an enumeration error.

Between 2 context menu openings, I clear the destination item list as the visible items depend on what a plugin reports (which is a ToolStripItem collection).

As ToolStripItem does not implement ICloneable, I can only see one solution: create a new item and copy the field values in code. But in this case, I cannot access the event handlers (at least the OnClick handlers should be copied).

Is there a generic solution that doesn't make me derive the ToolStripItems I don't want to restrict the plugin writers to use my own custom ToolStripItem class...

Thanks for any tips,
Gabriel


Answer this question

ToolStripItems: how to duplicate?

  • Scott Yost

    Thanks for the tips although they doesn't help much :(

    I don't want the context menu to show in the main menu. As I've considered cloning already (tried my light-weight cloning sooner) the problem still remains: cloning public fields is easy but the most important part, the Click event handler, still is not accessible for reading from outside (the Events collection, protected, IIRC).

    If I understand correctly, it's impossible to pass a context menu structure from a class to another and still retain the original (reference) menu. And by passing I understand passing it with the events still attached. The plugin is in an assembly, the GUI in another.

    I'll implement an alternate (dirty) solution then, passing a collection of generic handles + titles and creating the menu in GUI code. Any better ideas

    Gabriel

  • Santhosh_kumar

    If you look closer at the implementation of Clone, you'll see all the event handlers are copied over by this line:

      menuItem.Events.AddHandlers(this.Events);


  • Barry32Hayes

    Indeed, my mistake... I didn't see that.

    But, again, using a derived class would stop me from using the VS designer in the plugin project, right I mean, I'll need to create all the menus in code, using the clonable menuitem class instead of the framework one... After many tries of alternate ideas, I think I'll be forced to make this sacrifice.

    Thanks again,
    Gabriel

  • boaz_b

  • SQL Newbie

    You can use custom items at DesignTime. Select the down arrow in the TypeHere node to pick your custom item.
  • ToolStripItems: how to duplicate?