The resolution of the problem if fairly easy. You cannot copy event instances, you can copy delegate instances.
Events are designed exclusively to introduce some limitations over delegate instances, in order to make event handling more fool-proof then delegates. The members
are events, so — in particular — they cannot copy. In general, the idea to change event handlers (that is event's invocation lists) on the fly hardly can get robust code. Now, let's assume you and me are not fools. Keep reading.
Your problem is very natural. You simply need to have some set of actions abstracted from the UI. Same action can happen on the button click, main menu item click or context sensitive menu item click; in the last case the same instance of the context menu can behave differently depending on the context. You can have pretty complex flow of events which effect all those controls: they can get hidden, renamed or disabled. Your requirement to the technology is to make it all abstracted from the UI controls/items: hidden, renamed or disabled should be abstract actions, not UI controls/items; in this way controls/items associated with identical abstract actions would behave consistently without using any ad-hoc programming, automatically.
So, do exactly this: introduce a notion of… let me name it —
(not to mixed with (
). The type of
should include delegate instance (remember, me and you are not fools, so we can allow it), some status information (current name, enabled or not, hidden or not, any other states which you can encapsulate in one status word (use bit-mapped enumeration) and a containers of references to UI elements: for example, a container of instances of
and instances of
. Make some container of
items. Each time you add an instance of control/item to a command action, the appropriate UI
event is "assigned" to the delegate of appropriate
instance. After each command, make a global update which should update all UI elements based on the status of the instances of
This is just a sketch. In this way, we created loose coupling between abstract actions and UI. When you code semantic behavior, you should work only with your container of
and never directly with UI controls/items. You will have more freedom while working with delegate instances (remember, me and you are not fools).
Now, let's go deeper. To make things even more consistent and go away from ad-hoc programming even more fundamentally, you need to study the following architectural design patterns
Model View ViewModel: http://en.wikipedia.org/wiki/Model_View_ViewModel
On loose coupling
, read http://en.wikipedia.org/wiki/Loose_coupling