Search code examples
winformsmvp

How should I add controls when using WinForms and MVP?


We're using the MVP design pattern here, and we've gone with the presenter-per-UserControl style.

This answer suggests two different styles of presenter construction:

  1. Each presenter instantiates any child presenters that it has.
  2. A controller class instantiates all the presenters and handles communication between them.

Unfortunately there's no mention of how and where the view is wired up. In another project I'm using the factory pattern to create my presenters and pass them views using dependency injection. The views are created in a view factory that instantiates the views with their appropriate UserControls which are then added to the form with Controls.Add.

From what I gather from the first link, the Visual Studio designer is used to add the UserControls - which is fine, but then it seems that the presenters would be unnecessarily coupled to the view layer.

So how should I add my subviews and wire up the View-Presenter pair?


Solution

  • The way I tend to do this is I put a placeholder in the "master" view for the sub views, I normally use a panel control.

    I always wire up my MVP so that the Presenter creates the view. Never the other way round (I hate that style) The presenter then exposes a GetView() method that returns the view.

    The master presenter can then create a sub presenter get its view and tell the master view to render it. This is done through a method on the masterview that adds the sub view to the controls collection of the panel control.