Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Events between many forms - Publisher/Subscriber

Status
Not open for further replies.

loliloli

Programmer
Jun 22, 2011
2
BG
I want to define message, which a set of forms to listen for it, and each of them to raise.
For example:
BaseForm:Form{
publuc event EventHandler DataChanged;
protected virtual void OnDataChanged
{
if(DataChanged != null)
DataChanged(this, new EventHandler());
}
ChildForm:BaseForm
listen for the message
SecondForm:BaseForm
listen for the message and raise message

What is the schema for this. Something like SendMessage, PostMessage and WinProc in C APIs
Any Ideas!
 
The complexity depends on how much data you are trying to send back and forth.

This is what is known as the "Observer Pattern". You will need to keep a listing of all of the forms/class instances that need to be notified when X happens.

Start writing code and when you get stuck post code bits.

Lodlaiden

A lack of experience doesn't prevent you from doing a good job.
 
Thanks you for the reply!
I read for this model and make a small project to test it. It's seem to work but I used static array in the base class of the forms. It's not very good idea, I think. Some other idea to avoid this.
 
 http://www.mediafire.com/?332q8qshaa00fyj
I like to handle this scenario using the concept of an event broker. this way the individual UI components are not dependent on one another.

I put together a simple broker using Castle Windsor. The primary focus was extending castle Windsor more than the event broker, but the idea is there. source is hosted on github.

an example of what a form or user component might look like
Code:
class ThisUserControl 
   : UserControl
{
   private readonly IEventBroker broker;

   public MyForm(IEventBroker broker)
   {
       this.broker = broker;
   }

   private void MyForm_ButtonClick(object sender, EventArgs e)
   {
       var message = new DoSomethingImportant
                          {
                             Text = "...", 
                             Date = DatePicker.SelectedDate, 
                             Number = int.Parse(Spinner.Value)
                          };
       broker.send(message);
   }
}

public class ThatUserControl 
   : UserControl
     , IListener<ImportantMessage>
{
   public void Handle(ImportantMessage message)
   {
        use message to update this user control.
   }
}
code for the event broker & castle windsor:


Jason Meckley
Programmer

faq855-7190
faq732-7259
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top