This is a common problem and I've found the easiest solution is to place the 'shared' code inside a MenuFeature
class that inherits from ToolStripMenuItem
.
You still have to create 2 instances of this class, but each instance is very lightweight and only has code for any differences between the 2 usages (i.e. the ContextMenu item might use ToolStripItemDisplayStyle.ImageAndText
, while the ToolStrip item might use ToolStripItemDisplayStyle.Image
).
This allows common code to exist only once inside your custom MenuFeature
class, but still allows changes local to each usage of this menu item.
If you wanted to automatically synchronize properties like Enabled
/Visible
/etc, you could maintain a static collection of all instances inside the constructor, and then update all the items using events like EnabledChanged
/etc. I would recommend against this, however, as I've found different instances of the same menu 'feature' often need their own state - but this is getting out of scope on this Question, those interested in how I've managed items can comment on this answer or PM me.