I have a winform winform1 and 2 user controls control1 and control2 on this form
Now I want to define a custom event, which is raised/fired in control1 and received in control2. The event should be global and not directly defined in control1. control2 should not know about the existence of control1. The event should also be raised by other controls. How is the C# code for that? Do I need something like a publisher class?
You can use a static event:
Subscribe in the usual way:
Fire as you see fit:
What you describe looks like the Mediator pattern, in which objects communicate through messages. These messages can be implemented as events, callbacks, or any other mechanism.
You could use an implementation like MVVM Light's
Messenger
class (this framework is intended for use with WPF and Silverlight, but you can get the code for this particular class and use it in WinForms)A big advantage of the
Messenger
class over a static event is that it uses weak references, so it doesn't prevent garbage collection of subscribed objects, which reduces the risk of memory leaks.See this link for details about the
Messenger
classSo you can make your form publisher(and a mediator between controls), and all of your controls will be subscribers that will be notified on event.
An event occurred in a control, form will be notified and event handler on form will notify other controls that subscribed to this event.