5,693,936 members and growing! (16,405 online)
Email Password   helpLost your password?
Development Lifecycle » Design and Architecture » Design Patterns     Intermediate License: The Code Project Open License (CPOL)

WinForms Model View Presenter

By cgreen69

An introduction to using the MVP pattern with WinForms.
C#, Windows, .NET, Visual Studio, Architect, Dev, Design

Posted: 4 Jul 2006
Updated: 11 Aug 2008
Views: 64,739
Bookmarked: 89 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
21 votes for this Article.
Popularity: 5.08 Rating: 3.84 out of 5
2 votes, 9.5%
1
1 vote, 4.8%
2
2 votes, 9.5%
3
6 votes, 28.6%
4
10 votes, 47.6%
5

Introduction

The terms "Model View Controller" and "Model View Presenter" (MVP) are used to describe patterns that have been in use for some time in other technology areas but have recently come to the fore in the C# world.

The Model View Presenter is a derivation of the Model View Controller pattern. With modern ides such as Visual Studio inserting event handling into what we refer to as the view, it makes sense to leave them there rather than trying to implement them on a controller.

I struggled to find a simple MVP example on the web that was geared towards C# WinForms, and after reading Bill McCafferty's excellent article on MVP within ASP.NET, I decided to throw my hat into the ring.

I'm going to concentrate on the code. For a background on MVP, I suggest you try this link:

Why MVP?

The Model View Presenter pattern is designed to abstract the display of data away from the data and associated actions (e.g., saving the state). This, in theory, should make testing easier and more relevant, and remove the tight coupling typically found between data and forms within the Windows environment.

The View

The View is a user control that inherits from System.Windows.Forms. Its role in life is to display whatever data we are interested in. It contains no logic other than raising an event should the data change and any processing particular to the View such as closing itself happens. It doesn't care if anybody is listening to the event, it simply raises the event and has fulfilled its purpose. The View implements an interface that exposes fields and events that the Presenter needs to know about.

public class UserView : Form, IUserView

The Model

It is a representation of the data being manipulated. In my simple example, this a user object. The Model should implement an interface (IUserModel) that exposes fields that the Presenter will update when they change in the View.

public class UserModel : IUserModel

The Presenter

The Presenter marries the View to the Model. When first called, it updates all the properties of the View to correspond to the Model. Furthermore, it binds the View's events to methods in itself. Typically, the Presenter will update the Model based on changes in the View. Once a user has finished making changes in the View, the Model should be in sync and will be saved down correctly. The Presenter does not require an interface.

public UserPresenter(IUserModel model,IUserView view)
{
    this._model = model;
    this._view = view;
    this.SetViewPropertiesFromModel();
    this.WireUpViewEvents();
}

In my example, I use Reflection to iterate through the properties of the View / Model and update the corresponding field. Reflection is slow, but I haven't experienced any tangible slow down in any of my Windows apps yet - it would be easy to pass through a reference to the specific property being updated if speed starts to become an issue.

Putting it Together

IUserModel model = new UserModel();
IUserView view = new UserView();
new UserPresenter(model,view);
view.Show();

The code to get the ball rolling is simplicity itself, as shown above.

Testing

The example with this article includes some tests. Because our Presenter expects interfaces as opposed to concrete objects, it allows us to perform dependency injection with stubs and mocks, should we choose.

[Test]
public void DoesViewCorrespondToModel()
{
  StubView stub = new StubView();
  new UserPresenter(this._mock, stub);

In my tests, I have a StubView that implements the IUserView interface. I then instantiate a mock object representing the Model and perform testing on that. My tests check that the View shows what's in the Model and that the Model is updated when the View changes. You would, of course, include more tests in a real world project.

My stub implements Event Mocking, e.g.:

public void FireDataChanged()
{
    if (this.DataChanged != null)
    {
        this.DataChanged(null, EventArgs.Empty);
    }
}

From within my test, I simply call 'FireDataChanged' to recreate what would happen when a user changes any of the data in my View from within the application.

A Word on DataBinding

You may be wondering why I go to the trouble of implementing code in the Presenter to update the Model / View when Microsoft kindly provides us with databinding technology to bind data to Windows controls. The great thing about databinding is that it removes the need for having to write code in every Presenter to take care of the state, thus speeding the development cycle.

The problem with databinding is that it breaks our encapsulation by tightly coupling the 'View' to the data. Also, it cannot be tested from within an NUnit environment. However, one still needs to write laborious code within the Presenter to keep the Model in sync with the View. I hope that the code example I have provided you with that uses Reflection will ease this pain. Simply expose the data you require in the View and Model interfaces, and it should all be taken care of for you.

I am not a pattern zealot; you may find that given time constraints and the nature of a task you need to perform, a tightly bound view using databinding is the best option - however, I would encourage the abstraction of logic from presentation and the use of tests wherever possible.

Refactoring the Interfaces

It became apparent in the development of this article that a lot of property definitions are shared between the IView and IModel interfaces. In fact, every editable data property exposed on the Model needs to be implemented on the View; you may, therefore, like to consider implementing an additional interface called ICommonFields that is implemented by both IModel and IView. The benefit of this approach is that one only needs to add a new property to a single interface for the compiler to insist on its implementation in both the Model and the View.

Finally

Using MVP within WinForms is a learning curve, and I am keen to hear constructive criticism from anyone who thinks the example I have provided can be improved. By sharing knowledge, we all gain.

Credits

The MVP pattern has been developed by many coders over a long period of time. Martin Fowler presents that knowledge in a nice concise form on his website (link at the top of the article).

Thanks to Bill McCafferty for investing so much time in the article he wrote about MVP in ASP.NET (link at the top of article) which inspired me to submit a WinForms focused article.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

cgreen69


A .net devotee specialising in Object Orientated web development for financial institutions in Europe. When not working can normally be found at a bar within walking distance of the office.
Occupation: Software Developer (Senior)
Location: United Kingdom United Kingdom

Other popular Design and Architecture articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 28 (Total in Forum: 28) (Refresh)FirstPrevNext
GeneralOn databinding vs. decouplingmemberArtem Smirnov10:07 20 Aug '08  
QuestionIUserViewmemberMember 308313918:29 19 Jun '08  
AnswerRe: IUserViewmemberke4vtw18:53 10 Sep '08  
GeneralModel-View-Presenter frameworksmemberOleg Zhukov12:27 24 Apr '08  
QuestionWhy is your UserPresenter in the Library namespace but in the MVP folder? [modified]memberDao-Huy Hua5:02 15 May '07  
GeneralArticle UpdatememberMarkus Klieber8:34 17 Apr '07  
GeneralWhy not just use a generic presenter and pass property namemembernji7815:28 12 Apr '07  
GeneralRe: Why not just use a generic presenter and pass property namemembercgreen6910:13 15 Apr '07  
GeneralRe: Why not just use a generic presenter and pass property namemembernji7810:04 23 Apr '07  
GeneralRe: Why not just use a generic presenter and pass property namemembercgreen6911:14 24 Apr '07  
GeneralAdditional Questionmembercdx1135613:10 22 Dec '06  
GeneralRe: Additional Questionmembercgreen696:58 23 Dec '06  
GeneralRe: Additional Questionmembercdx113567:21 23 Dec '06  
GeneralRe: Additional Questionmembercgreen694:14 29 Dec '06  
GeneralRe: Additional Questionmembercdx113569:06 28 Dec '06  
GeneralRe: Additional Questionmembercgreen694:18 29 Dec '06  
GeneralUser Custom attribute for mappingmemberZiming2:03 8 Dec '06  
GeneralUserPresenter adjustedmemberSwiss Thomas8:24 26 Aug '06  
GeneralI like your examplememberMaruis Marais0:57 12 Jul '06  
Generalhow funnymemberc4tes6:09 7 Jul '06  
GeneralBroken link?memberMarc Leger15:48 4 Jul '06  
GeneralRe: Broken link?membercgreen6923:25 4 Jul '06  
GeneralRe: Broken link?membervl950t23:27 4 Jul '06  
GeneralRe: Broken link?membercgreen690:18 5 Jul '06  
GeneralA questionmemberGriffonRL13:22 4 Jul '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 11 Aug 2008
Editor: Smitha Vijayan
Copyright 2006 by cgreen69
Everything else Copyright © CodeProject, 1999-2008
Web19 | Advertise on the Code Project