thetemplar
thetemplar

Reputation: 97

C# event distribution

I have a WinForm with modular/dockable subforms (WeifenLuo). What is best practice to pass events/information between the forms?

For example: I want a "SelectionChanged" event in SubForm1 change what is highlighted in SubForm2. Problem is, there might be zero SubForm2-Tabs, one or multiple instances.

Currently, if a new instance of a SubForm is requested by the user, a function like this is called:

    private void toolStripMenuItemSubForm1_Click(object sender, EventArgs e)
    {
        SubForm1 subForm1 = new SubForm1();
        subForm1.Show(dockPanelMain, DockState.Document);
    }

The MainForm has no record of all subforms except dockPanelMain.Contents.

Edit: I know how forms can interact with each other and how events per se work. My problem is that a event from SubForm1 can alter different other SubForms, but they might not exist at a given point in time, or there might be multiple instances and I dont want to chain it through the MainForm for every single event.

Upvotes: 1

Views: 220

Answers (2)

Irwene
Irwene

Reputation: 3035

IMHO, you're taking this the wrong way around

A teacher used to present me this kind of problems this way : "A CEO does not necessarily know everybody who works for him. However, every worker will know it's CEO" (pardon the phrasing, it's (hastily) translated)

This could be applied to your problem as well :

Pass the parent instance to the childrens that will have the responsibility to hold into this instance and subsribe to the events that they should be listening to.

This way, your parent class will only have to take care of raising the events, the childrens will do the work of updating themselves

EDIT:

To work between the dockpanel's content classes it's basically the same thing.

Pass the Contents property of the dockpanel to the child classes. Since it's a collection (and thus a reference type), the child classes will always have access to the latest 'version' of the collection.

You'll just have to get all the instances that are of interest for you by filtering this collection

Filtering example (I may have missed a cast at the end) :

IEnumerable<SubForm2> sf2 = dockContents.Where(sf => sf is SubForm2)

Upvotes: 3

auburg
auburg

Reputation: 1475

I suggest passing an Event class that contains an event / delegate into your Subform constructor. Each subform can subscribe to events that are raised at the appropriate time.

Upvotes: 0

Related Questions