Winforms – How would you implement MVC in a Windows Forms application


I don't develop too many desktop / Windows Forms applications, but it had occurred to me that there may be some benefit to using the MVC (Model View Controller) pattern for Windows Forms .NET development.

Has anyone implemented MVC in Windows Forms? If so, do you have any tips on the design?

Best Solution

What I've done in the past is use something similar, Model-View-Presenter.

[NOTE: This article used to be available on the web. To see it now, you'll need to download the CHM, and then view the file properties and click Unblock. Then you can open the CHM and find the article. Thanks a million, Microsoft! sigh]

The form is the view, and I have an IView interface for it. All the processing happens in the presenter, which is just a class. The form creates a new presenter, and passes itself as the presenter's IView. This way for testing you can pass in a fake IView instead, and then send commands to it from the presenter and detect the results.

If I were to use a full-fledged Model-View-Controller, I guess I'd do it this way:

  • The form is the view. It sends commands to the model, raises events which the controller can subscribe to, and subscribes to events from the model.
  • The controller is a class that subscribes to the view's events and sends commands to the view and to the model.
  • The model raises events that the view subscribes to.

This would fit with the classic MVC diagram. The biggest disadvantage is that with events, it can be hard to tell who's subscribing to what. The MVP pattern uses methods instead of events (at least the way I've implemented it). When the form/view raises an event (e.g. someButton.Click), the form simply calls a method on the presenter to run the logic for it. The view and model don't have any direct connection at all; they both have to go through the presenter.