Reputation: 569
I'm new to the whole winforms programming. In the beginning, it seemed like all the code was ending up I'm the main form class. So i searched up how you're meant to organize code in winforms apps.
One solution I am trying right now is separate parts of the interface into user controls.
The problem is I'm not sure of the best way to communicate between controls and the main form. For example. Lets say I have a shape drawing type editing app. There's the main form and a user control which draws the objects. The main form holds the objects. And the user is able to select objects to edit and the selected object needs to be highlighted. So every time the selection changes, the main form has to tell the display control which object is now selected. Imagine if I had several user controls that needed to know information about the state in the main form. Every time something changed I'd have to call functions in all the controls to let them update. So in addition to the main form having to store a reference to the selected object all the controls are storing it as well. And i have to make sure they are all updated.
Another issue I have is that, I have a user control that lets you set properties of objects such as size or color. In order for the main form to know that a property changed, I need a custom event for each changeable setting, and then raise those events whenever a text box or checkbox changes and pass the value back. This seems like a lot of extra work. If everything was on the main form it would be so much easier. But then the main form class would be a million lines.
Am I going about all this the wrong way?
Upvotes: 1
Views: 2266
Reputation: 942
Rewinder is correct in that you should use events and INotifyPropertyChanged to handle all of the communication in the scenario you described.
Additionally, for the portion of the question in the second paragraph, why bother with an event for each setting? Use a single event with your own custom parameters that lets the subscriber of the event know exactly what was changed. You would still need to handle the various cases in the event handler, but it would certainly simplify things.
Upvotes: 3
Reputation: 14387
You can make your controls bind to an event on the main form. You can then raise that event from the main form and all your controls will be notified.
If you want to make the main form aware of changing properties in objects, you could implement the INotifyPropertyChanged interface on your objects. See here.
Upvotes: 1