views:

74

answers:

2

I'm working with a bit of code that is structured thusly:

Form A has user controls B and G within it. User control B has User control D within it, and user control D has a "refresh" method. User control G has user control F within it, and user control F needs to call the "refresh" method in D.

1) Short of restructuring the code (It's legacy code, so it's off the table as an option), are delegates the best way to go about handling this issue? If not, do you have another suggestion?

2) I have no experience with delegate functions -- is there a good primer or example that I could use to adapt to my code to achieve the desired functionality?

+4  A: 

First, F should not know anything about D and its refresh function. Add event to F, which is raised when necessary. If form A knows about F, subsctibe to this event from A. If not, make similar event in G, and subscribe to it in A. In A event handler, call Refresh directly, or call B method, which calls D.refresh.

It looks like my answer is even less readable than your question :) It should look like this:

F raises event -> G handles F's event and raises event -> A handles G's event and calls B method -> B method calls D.refresh

Alex Farber
@Raven you are on the right track with delegates. Events are declared using delegates so learning delegates first is a good idea.
P.Brian.Mackey
A: 

For delegates see this : http://www.akadia.com/services/dotnet_delegates_and_events.html

For events you have to make sure that stuff passes through in right order. In current scenario, Im guessing that a good way would be to expose an Event from G which should get triggered when something in F changes. And we will have a handler subscribed to this event in B which will eventually call refresh. There will be a few more events and delegates involved to pass the calls from parent to child and vice versa. Keep in mind the concept of a mechanical device: part which STARTS the movement is the one who triggers(raises event) to others. When others move they trigger other related parts...and eventually something far away moves. Hope it helps.

mishal153