Click to See Complete Forum and Search --> : Decoupling GUI from logic question


SlipperySlope
October 14th, 2008, 03:28 PM
I have a simple program that comprises a simple GUI (one form) that has a SerialPort object.

A button on the GUI activates the SerialPort's Send method

An event fired by the serialPort object 'listens' for the reply

// When data is recieved through the port, call this method
SerialPort.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);

The port_DataReceived method amongst other things writes the data received to the GUI

Now I want to decouple the GUI from the Logic
If the GUI object creates a Logic object, it can call the Send method no problem.

question is: what is the best way to get the GUI notified that the Logic has received a message given that the Logic doesnt know anything about the GUI?

TheCPUWizard
October 14th, 2008, 03:34 PM
Your post contains the answer.....

How does the SerialPort object let your program know that data is there....when it is obvious that the writers of the serial port object had absolutely no knowledge about your program (or even your existance in all likelyhood....)

darwen
October 14th, 2008, 03:35 PM
Your logic should be in a separate class. Implement an event on your class which the GUI hooks into.

e.g.


public class SerialPortLogic
{
public delegate void MessageReceivedHandler(object sender, byte [] data);

public event MessageReceivedHandler MessageReceived;
}


There's a tutorial on custom events here : http://msdn.microsoft.com/en-us/library/aa645739(VS.71).aspx.

Darwen.

SlipperySlope
October 14th, 2008, 03:49 PM
Thanks for replies.

what I am not understanding at the mo is - if the Logic object creates the SerialPort object then the port_DataReceived method in Logic can do its stuff (write to a database) but cannot assign to the GUI as it knows nothing of that. I need a 'listener' in the GUI object too somehow?

Confused, guess I need to do some more reading, will look at that msdn link.

TheCPUWizard
October 14th, 2008, 03:53 PM
Your logic should be in a separate class. Implement an event on your class which the GUI hooks into.

Ahhhh.you gave it away....

By the way...Your code is the OLD (.Net 1..x), the following is recommended for 2.0 and later...

public class SerialPortLogic
{
public class MessageArgs : EventArgs
{
// necessary data.
}
public event EventHandler<MessageArgs> MessageReceived;
}

boudino
October 15th, 2008, 03:28 AM
An event is the answer. In the Logic class, provide an event which will be fired if data is recieved and written to db. GUI can register an event handler with this event and Logic still doesn't know anything about the GUI or whoever is registered to the event. It just fire it regarless how many event handlers are attached to it. And of course, you can provide some extra information in the event args, as it was sugested before.