Raise custom events in C# WinForms

余生颓废 提交于 2019-12-04 02:16:48

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!