views:

186

answers:

5

Hello there,

what's the best/proper way of interacting between several windows in C# app? Recently, I've run into a problem where one of program windows has to call method modifying main window. My solution was to create factory-like class, that would arrange all underlying model-data and organize the communication between various windows (through delegates). However, as passing one or two delegates was not a problem, I started thinking what if my other windows would need 10 delegates to interact properly with main window? Are delegates good solution? How to pass them in good way - through constructor, properties? Or maybe the need of using that many delegates is some serious design flaw itself?

A: 

If it's only needing to interact with the main window, why not give a reference to the main window in the constructor of the others?

public class MainForm : Form
{
}

public class OtherForm : Form
{
    protected MainForm MainForm { get; set; }

    public OtherForm(MainForm mainForm) : base()
    {
        this.MainForm = mainForm;
    }
}

EDIT:

Simple and effective.

If your forms need to interact with all the other forms of the application, then a service locator type pattern might be better suited.

Sekhat
Doing this in a base SubForm would be better.
yapiskan
t'was a brief example :)
Sekhat
I see. And that was just a brief comment :)
yapiskan
A: 

Previously with MFC, there was something that notify all windows. You will pass an event id with a parameter.

You could do something similar with one delegate that will expose an event id and a collection of parameter.

The greatest advantage of this is that windows only have to implement one gateway.

Hapkido
A: 

You can use a single delegate, using a custom EventArgs to pass several informations, like: type of notificaton, additional parameters, etc.

xoreax
+2  A: 

You need to split the Model from the view by a Controller. Put an object that will be able to have both form reference and that will be able to manage the shared information.

An other solution is to send the reference of the formX to the formY this way they can communicate.

Daok
+1  A: 

We use a custom built forms manager that uses the subject/observer pattern.

Every form that is opended is reported to the FormsManager, the FromsManager makes itself an observer of the form.

It also makes the form an observer of the FormsManager.

So you end up with every form observing the FormsManager and the FormsManager observing every form. Each form can then communicate to any other form via the FormsManager without each form having to be aware of all the others.

Si Keep
I believe that's what I'm looking for - as my data is displayed in various ways (multiple windows - which somehow need to communicate) observer patter sounds like perfect solution. Thanks a lot!