best practices to call methods in the parent form and access gui elements in parent form in c#

后端 未结 3 482
刺人心
刺人心 2021-01-12 05:18

I am developing a win form app and I found myself constantly requiring to access methods in my parent form say Form1 from another class be it a form class or just a class. I

3条回答
  •  执念已碎
    2021-01-12 06:00

    Raising events, as suggested by Kragen and Richard will work, and stops the parent/child relationship from being as tightly coupled, but if you want something really flexible, look into the Event Aggregator pattern. There is a nice one provided in the Prism project here, although a lot of people find it inconvenient to use, and have created extensions in order to make it easier to work with such as this, or written their own from scratch such as this.

    Basically, the idea is that the parent doesn't even care that the message came from its child window. The child window has merely thrown a message such as "Open Order #6" onto the message bus, assuming that someone else will handle it, pretty much the same as raising an event. Elsewhere, the parent form, which is responsible for containing all the child forms has subscribed to "Open Order" messages, and so it receives the message, and opens a new child window for Order #6.

    Since the parent isn't directly "welded" to the child anymore, it's possible for these messages to originate elsewhere as well, now. You could raise "Open Order" messages from a most-recently-used list on the parent form itself, or in reaction to a hyperlink in some other form being clicked. It no longer matters who asked for order #6 to be opened, only that someone did. It's a highly flexible model that eliminates a lot of tight coupling.

提交回复
热议问题