Listening to Events in Main Form from Another Form in C#

后端 未结 3 1926
Happy的楠姐
Happy的楠姐 2020-12-20 00:35

I have an application that has a main form and uses an event handler to process incoming data and reflect the changes in various controls on the main form. This works fine.

3条回答
  •  粉色の甜心
    2020-12-20 00:49

    Consider using loosely coupled events. This will allow you to couple the classes in such a way that they never have to be directly aware of each other. The Unity application block comes with an extension called EventBroker that makes this very simple.

    Here's a little lick of the sugar:

    public static class EVENTS
    {
        public const string UPDATE_TICKED = "event://Form1/Ticked";
    }
    
    public partial class Form1 : Form
    {
        [Publishes(EVENTS.UPDATE_TICKED)]
        public event EventHandler Ticked; 
    
        void the_timer_Tick(object sender, EventArgs e)
        {
            // I would like code in here to update all instances of SecondaryForm
            // that happen to be open now.
            MessageBox.Show("Timer ticked");
            OnTicked();
        }
    
        protected virtual void OnTicked()
        {
            if (Ticked == null) return;
            Ticked(this, e);
        }
    }
    
    public partial class SecondaryForm : Form
    {
        [SubscribesTo(EVENTS.UPDATE_TICKED)]
        private void Form1_Ticked(object sender, EventHandler e)
        {
            // code to handle tick in SecondaryForm
        }
    }
    

    Now if you construct both of these classes using Unity, they will automatically be wired together.

    Update

    Newer solutions use message bus to handle loosely coupled events. See http://masstransit-project.com/ or http://nimbusapi.github.io/ as examples.

提交回复
热议问题