Writing a global custom event in C#

后端 未结 3 1773
孤城傲影
孤城傲影 2020-12-09 06:17

I have a winform winform1 and 2 user controls control1 and control2 on this form

Now I want to define a cu

相关标签:
3条回答
  • 2020-12-09 06:35

    So 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.

    0 讨论(0)
  • 2020-12-09 06:58

    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)

    // Register for a specific message type
    Messenger.Default.Register<TypeOfTheMessage>(this, DoSomething);
    ...
    
    // Called when someone sends a message of type TypeOfTheMessage
    private void DoSomething(TypeOfTheMessage message)
    {
        // ...
    }
    
    // Send a message to all objects registered for this type of message
    Messenger.Default.Send(new TypeOfTheMessage(...));
    

    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 class

    0 讨论(0)
  • 2020-12-09 07:01

    You can use a static event:

    public static class MyGlobalEvent {
        public static event EventHandler MyEvent;
    
        public static void FireMyEvent(EventArgs args) 
        {
            var evt = MyEvent;
            if (evt != null)
                evt(args);
        }
    }
    

    Subscribe in the usual way:

    MyGlobalEvent.MyEvent += args => Console.WriteLine("Event Was Fired.");
    

    Fire as you see fit:

    MyGlobalEvent.FireMyEvent(new EventArgs());
    
    0 讨论(0)
提交回复
热议问题