Raise custom events in C# WinForms

前端 未结 1 760
眼角桃花
眼角桃花 2021-02-14 05:53

I have some Events I created on my own and was wondering on how to raise them when I want.

Probably my application design is also messed up, might take a look at that if

相关标签:
1条回答
  • 2021-02-14 06:32

    Edit : It seems your question is more about hooking into a specific event, but FWIW below is how to fire custom events in general.

    Handling the TextBox Changed Event

    From what I understand, you want an external party to monitor events raised from a textbox on a Form and then to reload data on another form?

    A quick and dirty would be to make the Form TextBox public and then others could subscribe to this event

    MainForm.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
    

    OR, in more recent versions of C#:

    MainForm.textBox1.TextChanged += this.textBox1_TextChanged;
    

    Adding Your own Custom Event

    Another, cleaner way would be to raise a custom event, - e.g. MyDataChangedEvent below. This will allow you to abstract away the fact that the changes are coming from a textbox at all.

    // Assuming you need a custom signature for your event. If not, use an existing standard event delegate
    public delegate void myDataChangedDelegate(object sender, YourCustomArgsHere args);
    
    // Expose the event off your component
    public event myDataChangedDelegate MyDataChangedEvent;
    
    // And to raise it
    var eventSubscribers = MyDataChangedEvent;
    if (eventSubscribers != null)
    {
       eventSubscribers(this, myCustomArgsHere);
    }
    

    You might also look at the Ent Lib Composite Application Block and Smart Client Software Factory - this has a very flexible event broking / pub sub mechanism for synchronising across UI "SmartParts" (controls, forms dialogs etc) in a loose-coupled fashion. (CAB is now very dated).

    0 讨论(0)
提交回复
热议问题