Sie sind auf Seite 1von 13

3/10/2014

Design Codes: MVVM for .NET Winforms MVP-VM (Model View Presenter - View Model) Introduction
6

Ms

Siguiente blog

Crear un blog

Acceder

Design Codes
Aviad Ezra on software architecture surroundings the .NET environment

Sunday, August 2, 2009

MVVM for .NET Winforms MVP-VM (Model View Presenter - View


Model) Introduction
This post introduces the MVP-VM (Model View Presenter Model View) design pattern, which is the windows
forms (winforms) equivalent of WPF/Silverlight MVVM. The MVP-VM pattern is best suited to winforms
applications that require full testing coverage and use data binding extensively for syncing the presentation with
the domain model.

About the Author Aviad Ezra is a Senior Software


Development Lead within Microsoft's
Skype Group based out of Redmond,
WA. He has over 13 years of experience
in building large, distributed software
systems. In his current role, Aviad is
working on scaling the Lync Online
Service. In previous roles, Aviad worked
on making Apache Hadoop runnable
and deployable on Windows/Azure

Evolution

(HDInsight). He lead a development

Before we start digging deep into MVP-VM, lets have a quick review of the patterns from which it has evolved.

designed and developed smart client

team building C4I/HLS systems. He


applications for cardiology labs, and
built automation systems, including
hardware and software for automated
testing of electronic circuits

Presentation Model

Pageviews last month

Martin Fowler introduced the Presentation Model pattern as a way of separating presentation behavior from the
user interface, mainly to promote unit testing. With Presentation Model every View has Presentation Model that
encapsulates its presentation behavior (such as how to handle buttonXXX click) and state (whether a check box is
checked/unchecked).

12,460
Design Patterns (10)
MEF (2)

Multi Threading (7)

MVC (3) MVP

(4) MVVM (4)

MVXX (7) Networking (7)


Silverlight (3) Testing (2) UML (6)

Popular Posts
UML Class Diagram: Association,

http://aviadezra.blogspot.com/2009/08/mvp-mvvm-winforms-data-binding.html

1/13

3/10/2014

Design Codes: MVVM for .NET Winforms MVP-VM (Model View Presenter - View Model) Introduction
Aggregation and Composition
MVVM for .NET Winforms MVPVM (Model View Presenter - View
Model) Introduction
Model View Presenter (MVP)
Design Pattern with .NET Winforms vs. ASP.NET Webforms
UML Sequence Diagram:
Interaction Fragment (Alt, Opt,
Par, Loop, Region)
Twisting the MVC Triad - Model
View Presenter (MVP) Design
Pattern
.NET Remoting Events (with C#
Code Sample).
.NET CLR Thread Pool Internals
UML Activity Diagram Modeling
Parallel Applications
Data Binding of Business Objects
in Visual Studio .NET 2005/8
Whenever the View changes it informs its Presentation Model about the change, in response the
Presentation Model changes the Model as appropriate, reads new data from the Model and
populates its internal view state. In turn, the View updates the screen according to the Presentation
Model updated view state.

The downside of this pattern it that a lot of tedious code is required in order to keep the Presentation Model and
the View synchronized. A way to avoid writing the synchronization code is to bind the Presentation Model
properties to the appropriate widgets on the View such that changes made to the Model will automatically reflect
on the View, and changes made by the user will automatically flow from the View, through the Presentation Model
to the underlying Model object.

MVVM (Model View View Model) for WPF


MVVM (Model View View Model) introduces an approach for separating the presentation from the data in
environments that empower data binding such as WPF and Silverlight (see Developing Silverlight 4.0 Three Tiers
App with MVVM). As you can see in the picture bellow, MVVM is almost identical to the Presentation Model
pattern, just instead of 'Presentation Model' we have 'View Model' and the two way data binding happens
automatically with the help of WPF/Silverlight runtime (read more).

Developing Silverlight 4.0 Three


Tiers App with MVVM and WCF
Data Services (OData via ATOM)

Blog Archive
2014 (4)
2013 (1)
2012 (1)
2011 (2)
2010 (7)
2009 (14)
October (2)
September (1)
August (2)
UML 2.0 Component
Diagrams
Modeling the
System L...
MVVM for .NET
Winforms MVPVM (Model View
Presen...
July (2)
June (3)
May (1)
April (1)
March (1)
February (1)
2008 (13)
2007 (1)

With WPF, the bindings between View and View Model are simple to construct because each View
Model object is set as the DataContext of its pair View. If property value in the View Model changes,

http://aviadezra.blogspot.com/2009/08/mvp-mvvm-winforms-data-binding.html

2/13

3/10/2014

Design Codes: MVVM for .NET Winforms MVP-VM (Model View Presenter - View Model) Introduction
the change automatically propagate to the View via data binding. When the user clicks a button in
the View, a command on the View Model executes to perform the requested action. The View
Model, never the View, performs all modifications made to the Model data.

MVP-VM (Model View Presenter - View Model)


Starting from .NET framework 2.0, Visual Studio designer supports binding objects to user controls at design time
which greatly simplifies and motivates the use of data binding in winforms applications. Even when designing
simple UI without the use of any fancy pattern it often makes sense to create View Model class that represent
the View display (property for every widget) and bind it to the View at design time. You can read all about it in
Data Binding of Business Objects in Visual Studio .NET 2005/8.
When creating .NET winforms application that consist of many Views that present complex domain model and
includes complex presentation logic - its often makes sense to separate the Views from the domain model using
the Model View Presenter pattern. One can use Supervising Controller or Passive View depending on the
required testing coverage and the need for data binding.
With Supervising Controller data binding is simple but presentation logic cannot be fully tested since the Views
(that are usually being mocked) are in charge of retrieving data from the Model. With Passive View the thin Views
allow full testing coverage and the fact that the Presenter is in charge of the entire workflow greatly simplify
testing. However, direct binding between the Model and the View is discouraged. For more details please refer to
Model View Presenter Design Pattern with .NET Winforms.
MVP-VM is about combining the two patterns so we wont have to give up on Data Binding nor cut down on
testability. This is achieved by adapting the Passive View pattern while allowing an indirect link between the
Model and the View.

MVP-VM Overview

The View is in charge of presenting the data and processing user inputs. It is tightly coupled to the Presenter so
when user input is triggered (a button has been clicked) it can directly call the appropriate method on the
Presenter. Its widgets are bound to the matching View Model properties such that when a property of the View
Model changes the linked widget is being changed as a result, and when the widget value changes the View
Model property is being changed as a result.
The View Model exposes properties that are bound to its matching View widgets. Some of its properties are
linked directly to the Model object such that any change made to the Model object automatically translate to
change on the View Model and as a result appear on the View and vise versa, and some of its properties reflect
View state that is not related to Model data, e.g whether buttonXXX is enabled. In some cases the View Model is
merely a snapshot of the Model object state so it exposes read-only properties. In this case the attached widgets
cannot be updated by the user.
The Presenter is in charge of presentation logic. It creates the View Model object and assign it with the
appropriate Model object/s and bind it to the View. When its being informed that a user input has been triggered it
executes according to application rules e.g. command the Model to change as appropriate, make the appropriate
changes on the View Model etc. It is synchronized with the Model via Observer-Synchronization so it can react to
changes in the Model according to application rules. In cases were its more appropriate for the Presenter to
change the View directly rather than though its View Model, the presenter can interact with the View though its
interface.
The Model is a bunch of business objects that can include data and behaviors such as querying and updating the
DB and interacting with external services. Such objects that only contain data are referred to as data entities.

http://aviadezra.blogspot.com/2009/08/mvp-mvvm-winforms-data-binding.html

3/13

3/10/2014

Design Codes: MVVM for .NET Winforms MVP-VM (Model View Presenter - View Model) Introduction

How does it Work?

As you can see in the figure above, each UI widget is bound to a matching property on the customer view model,
and each property of the customer view model is linked to a matching property on the customer data entity. So
for example, when the user changes the value of the Name textbox the Name property of the customer view
model is automatically updated via data binding, which causes the update on the Name property of the
customer data entity. In the other direction, when the customer data entity changes the changes reflect on the
customer data model which causes the appropriate widgets on the view to change via data binding.
When the user clicks on the Save button, the view responds and calls the appropriate method on the presenter,
which responds according to application logic, in this case - it calls the Save method of the customer dao object.
In cases where the application logic is more sophisticated, the presenter may bypass the view
model and make direct changes on the view through its abstraction. In some cases view model
property can be linked to view widget at one side but not linked to model object at the other side,
in such cases the view model will be prompt to change by the presenter, which will result in the
appropriate change on the view widget.

Case Study MVP-VM


In the following case study the MVP-VM pattern is used to separate the concerns of a simple application that
present list of customers and allows adding a new customer. Well focus on the Add Customer screen.

http://aviadezra.blogspot.com/2009/08/mvp-mvvm-winforms-data-binding.html

4/13

3/10/2014

Design Codes: MVVM for .NET Winforms MVP-VM (Model View Presenter - View Model) Introduction

Class Diagram Add New Customer

The AddCustomerPresenter holds references to AddCustomerViewModel, AddCustomerView and CusomerDao


(model). It references the AddCustomerViewModel and the AddCustomerView so it can establish data binding
between the two, and it references the CussomerDao so it can change it and register to its events.
The AddCustomerView holds reference to the AddCustomerPresenter so it can call the SaveClicked method
when the Save button is clicked.

Sequence Diagram - Initialization

The AddCustomerView is instantiated by some class in the application and injected with instance of the
CusomerDao (model), it instantiate the AddCustomerPresenter and injects it with the CusomerDao and with itself.
The AddCustomerPresenter prompts the CusomerDao to create a new CustomerDataEntity, instantiate the
AddCustomerViewModel injecting it with the newly created CustomerDataEntity, and calls ShowCustomer on the
AddCustomerView in order to data bind it to the AddCustomerViewModel.

Sequence Diagram - Saving New Customer

http://aviadezra.blogspot.com/2009/08/mvp-mvvm-winforms-data-binding.html

5/13

3/10/2014

Design Codes: MVVM for .NET Winforms MVP-VM (Model View Presenter - View Model) Introduction

The AddCustomerView responds to click on the Save button and calls the appropriate method on the
AddCustomerPresenter. The AddCustomerPresenter calls ReadUserInput on the AddCustomerView which in
response alerts its internal binding source to reset binding, which causes the content of its widgets to reread into
the AddCustomerViewModel (read more about data binding of business objects). The AddCustomerPresenter
than evaluates the CustomerDataEntity (which was updated automatically since its linked to
AddCustomerViewModel) and checks whether the new customer already exist in the data storage. In case there
are no duplications it commands the CusomerDao (model) to save the customer.
Heres the code:

View
1: public partial class AddCustomerView : Form, IAddCustomerView
2:
3:

{
private AddCustomerPresenter m_presenter;

4:
5:

public AddCustomerView(ICustomerDao dao)

6:

7:

InitializeComponent();

8:
9:
10:

m_presenter = new AddCustomerPresenter(this, dao);


}

11:
12:

public void ShowCustomer(CustomerViewModel customerViewModel)

13:

14:
15:

cusomerViewModelBindingSource.DataSource = customerViewModel;
}

16:
17:

public void ReadUserInput()

18:

19:
20:

cusomerViewModelBindingSource.EndEdit();
}

21:
22:

public void ShowError(string message)

23:

24:
25:

MessageBox.Show(message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);


}

26:
27:

private void m_btnSave_Click(object sender, EventArgs e)

28:

29:
30:

m_presenter.SaveClicked();
}

http://aviadezra.blogspot.com/2009/08/mvp-mvvm-winforms-data-binding.html

6/13

3/10/2014

Design Codes: MVVM for .NET Winforms MVP-VM (Model View Presenter - View Model) Introduction

31:
32:

private void m_btnCancel_Click(object sender, EventArgs e)

33:

34:

m_presenter.CancellClicked();

35:
36:

}
}

Presenter
1: public class AddCustomerPresenter
2: {
3:

private IAddCustomerView m_view;

4:

private ICustomerDao m_customerDao;

5:

private CustomerViewModel m_viewModel;

6:
7:

public AddCustomerPresenter(IAddCustomerView view, ICustomerDao customerDao)

8:

9:

m_view = view;

10:

m_customerDao = customerDao;

11:
12:

// Create the data entitry

13:

CustomerDataEntity customerDataEntity = customerDao.CreateCustomerDataEntity();

14:

CustomerViewModel customerViewModel = new CustomerViewModel(customerDataEntity);

15:
16:

m_viewModel = customerViewModel;

17:
18:

// Bind the ViewModel to the VIew

19:
20:

m_view.ShowCustomer(customerViewModel);
}

21:
22:

public void SaveClicked()

23:

24:

m_view.ReadUserInput();

25:
26:

CustomerDataEntity customerDataEntity = m_viewModel.CustomerDataEntity;

27:

bool duplicateExist = !IsDuplicateOfExisting(customerDataEntity);

28:

if (duplicateExist)

29:

30:

m_customerDao.Save(customerDataEntity);

31:
32:

m_view.Close();

33:

34:

else

35:

36:

m_view.ShowError(string.Format("Customer '{0}' already exist", m_viewModel.Name));

37:
38:

}
}

39:
40:

private bool IsDuplicateOfExisting(CustomerDataEntity newCustomerDataEntity)

41:

42:

CustomerDataEntity duplicateCustomerDataEntity =

43:

m_customerDao.GetByName(newCustomerDataEntity.Name);

44:
45:
46:

return duplicateCustomerDataEntity != null;


}

47:
48:

public void CancellClicked()

49:

50:
51:

m_view.Close();
}

52: }

ViewModel
1: public class CustomerViewModel
2: {
3:

private readonly CustomerDataEntity m_customerDataEntity;

4:
5:

public CustomerViewModel(CustomerDataEntity customerDataEntity)

6:

7:
8:

m_customerDataEntity = customerDataEntity;
}

9:
10:

public string Name

11:

12:

get { return m_customerDataEntity.Name; }

13:
14:

set { m_customerDataEntity.Name = value; }


}

15:
16:

public string CompanyName

17:

18:

get { return m_customerDataEntity.CompanyName; }

http://aviadezra.blogspot.com/2009/08/mvp-mvvm-winforms-data-binding.html

7/13

3/10/2014

Design Codes: MVVM for .NET Winforms MVP-VM (Model View Presenter - View Model) Introduction

19:
20:

set { m_customerDataEntity.CompanyName = value; }


}

21:
22:

public DateTime DateOfBirth

23:

24:

get { return m_customerDataEntity.DateOfBirth; }

25:
26:

set { m_customerDataEntity.DateOfBirth = value; }


}

27:
28:

public int Age

29:

30:

get

31:

32:

int age = DateTime.Now.Year - m_customerDataEntity.DateOfBirth.Year;

33:
34:

return age;

35:
36:

}
}

37:
38:

public CustomerDataEntity CustomerDataEntity

39:

40:
41:

get { return m_customerDataEntity; }


}

42: }

Download
The case study can be downloaded from here or here
Posted by aviade at 2:51 AM
Labels: Design Patterns, MVP, MVXX

37 comments:
Bhavtosh August 17, 2009 at 3:15 PM
informative article
Reply

ismell September 14, 2009 at 9:01 PM


Love the article!
Can you repost the case study project ?
The link seems to be dead.
Reply

aviade

September 17, 2009 at 6:04 PM

Thanks for the feedback and sorry for the inconvinience, i'd replaced my old online data storage provider
so you should be able to download the source code now.
Reply

Marom January 22, 2010 at 3:22 PM


An amazing article!!! Well explained and looks sharp.
I followed this design in my last application and got great feedbacks from the team.
Looking forward to your next post :-)
Thanks a lot! Keep it up
Reply

Anonymous August 27, 2010 at 11:29 AM


Great article
Now it looks so simple for me. Great screens/diagrams.
Love it.
Reply

http://aviadezra.blogspot.com/2009/08/mvp-mvvm-winforms-data-binding.html

8/13

3/10/2014

Design Codes: MVVM for .NET Winforms MVP-VM (Model View Presenter - View Model) Introduction
Anonymous October 12, 2010 at 12:07 PM
I did not understand why to use it. In fact this application can be build with 3-tier architecture as well,with
more simplicity of code.here i find more complicated code.can u explain me in better way.
Reply

Anonymous December 13, 2010 at 6:36 PM


Would you recomend , in simpler cases to merge Presenter and View model class.
I mean , if there is One PResenter and one ViewModel entity, I don't see any benefit to make two
separate classes.
We could simply bind the View to some properties exposed on the Presenter.
Reply

Johan January 28, 2011 at 11:33 AM


Thanks for the great article
Reply

aviade

March 26, 2011 at 9:29 PM

In simple cases, it make since to move the presenter functionality into the ViewModel, by that we
practically convert the pattern to MVVM.
The nice thing about MVPVM is that the ViewModels only contain properties that reflect the View state,
and it's the presenter responsibility to connect the View with the ViewModel and to handle actions and
events.
Since in winforms we usually use design time binding to bind the ViewModel to the View, I like it better
when the ViewModel is thin and free from handling actions/commands and events.
But, it's only a matter of personal taste, you can go either way :)
Reply

PhilChuang April 15, 2011 at 11:13 PM


Aviad, i've taken your MVP-VM concept and taken it a step further to make it true MVP - care to take a
look?
Developing WP7 apps using the MVP pattern
Basically take your MVP-VM pattern, but instead of the Form directly implementing the View interface,
and instead of the Presenter directly accessing the ViewModel, you create a View gateway class which
implements the View interface and passes calls to the Form and the ViewModel.
Reply

Anonymous May 10, 2011 at 11:36 AM


Great article
Can you repost the case study project?
The link seems to be dead.
Reply

Anonymous May 21, 2011 at 6:01 PM


I too would like to download the project
Reply

aviade

May 22, 2011 at 5:05 PM

10x
Since the project is uploaded to Google docs, you need to have Google account to download it through to
provided link.
I uploaded the project to SkyDrive and shared the link in the same place.

http://aviadezra.blogspot.com/2009/08/mvp-mvvm-winforms-data-binding.html

9/13

3/10/2014

Design Codes: MVVM for .NET Winforms MVP-VM (Model View Presenter - View Model) Introduction
If you still cannot download the project, send me an email and I will send you a copy.
Aviad
Reply

Anonymous June 1, 2011 at 4:19 PM


Greetings Aviad,
Awesome article. I'm new in the MVP/MVVM design world. Could you comment on how DTO's would fit
into your MVP-VM pattern or if they would even be necessary at all.
Thank you again
Reply

aviade

June 2, 2011 at 7:29 AM

Thanks for the feedback,


With MVP-VM, Data transfer objects (used to reduce the size of the serialized data sent to the server) will
be instantiated by the Presenter, as it is responsible for communicating with external/internal services and
repositories.
Reply

bikramiter October 3, 2011 at 12:01 PM


I tried to find a suitable architecture for my winform project. After experimenting a number of available
architectures, I finally decided to go with this one for its simplicity and ease of use.
Still I have a doubt regarding the CustomerDataMapper and what it does, because it seems near similar
to CustomerDao. Can you please explain the purpose of both. Also I want to implement EF4.1 as the
ORM, just give me simple guidelines for the same.
Finally I would like to thank you for this beautiful article.
Reply

Anonymous December 5, 2011 at 1:00 AM


I'm interested too in some Entity Framework guidelines. Thanks for the article Aviad.
Reply

Anonymous December 22, 2011 at 4:42 PM


This article is fantastic! It has completely changed the way I code in Winforms.
I have one question though... If I wanted to raise an event "SelectedCustomerChanged" after a different
customer is selected in the CustomersView, should I require that event in ICustomersView, then
implement and raise it in the CustomersView? Or should that logic be in the presenter? Thanks again!
Reply

aviade

December 22, 2011 at 5:28 PM

Thanks for the feedback.


The interface ICustomersView is intended to provide the Presenter with a way to change the View and
get data from the view. In your case, the View should handle the selected customer changed event, and
call CustomerChanged method on the presenter.
Reply

Anonymous December 22, 2011 at 5:53 PM


Ok got it... So then would it be safe to say that in my ICustomerView I would have:
event EventHandler CustomerChanged;
CustomerViewModel SelectedCustomer{get; set;}

http://aviadezra.blogspot.com/2009/08/mvp-mvvm-winforms-data-binding.html

10/13

3/10/2014

Design Codes: MVVM for .NET Winforms MVP-VM (Model View Presenter - View Model) Introduction
Then the process would go:
CustomerView.OnSelectedCustomerChanged() -> CustomersPresenter.CustomerChanged() --(updates-> CustomerView.SelectedCustomer
or is the last part a bit redundant... i figured the presenters CustomerChanged would do some validation
on the change then update the view's selected customer.
Thank you again for your feedback it is very much appreciated!
Reply

aviade

December 29, 2011 at 4:42 AM

Exposing SelectedCustomer through the View interface is the right thing to do given that the Presenter
needs to use it/change it. You don't need to expose event handlers in the View interface, the View should
handle the event and call the appropriate method on the Presenter.
Reply

Anonymous January 11, 2012 at 1:58 AM


This is an odd question but have you ever considered its use in a VSTO application. I am trying to find a
good framework to use for VSTO and this seems to have the best chance. Any thoughts? P.S. Incredible
Article!
Reply

fabiopand February 6, 2012 at 8:00 PM


Please, check out this article: http://msdn.microsoft.com/en-us/magazine/hh580734.aspx
I'm confused!
Reply

aviade

February 7, 2012 at 12:25 AM

This post introduces a way to make the MVVM pattern applicable for 'Windows Forms' applications. In the
post that you're referring to, the pattern is aimed for WPF.
In most cases, for Silverlight and WPF applications (xaml based), I would recommend to stick with MVVM
as it is an established and well known pattern that fits nicely to the data-binding features exposed in WPF
and Silverlight. In Windows Forms however, the data-binding mechanism is different (for example, there's
no automatic command propagation between the View and the ViewModel), so I found that it makes
sense to add the Presenter pattern to compliment the binding between the View and the ViewModel.
Reply
Replies
fabiopand February 7, 2012 at 2:35 PM
Fair enough, thanks for your help! Great article anyway!

Allen July 18, 2012 at 10:15 PM


Thanks! This is the best(clear and detailed) tutorial I've come across describing MVP
dataBinding with winForms.
Thanks again, much appreciated!

Allen July 18, 2012 at 10:17 PM


Thanks! This the best (clear and detailed) tutorial I've come across describing dataBinding
using MVP with winForms.
Thanks again, much appreciated!
Reply

http://aviadezra.blogspot.com/2009/08/mvp-mvvm-winforms-data-binding.html

11/13

3/10/2014

Design Codes: MVVM for .NET Winforms MVP-VM (Model View Presenter - View Model) Introduction
HOWARD February 10, 2012 at 8:12 PM
Good article! It is good to try MVVM pattern for winform, just like silverlight and wpf. Thank you.
Reply

Szymon Tengler February 7, 2013 at 9:15 PM


Nice article, but I have some doubts.
What If user click Cancel button when editing customer?
Then the model should be restored to original state. I don't see this solution.
Reply

RiverView March 26, 2013 at 9:52 PM


I have hunted high and low for this. Thanks!!!
Reply

williams chorolque April 24, 2013 at 4:38 AM


Szymon Tengler maybe you need to implement the IEditableObject on CustomerViewModel like this
http://msdn.microsoft.com/es-es/library/system.componentmodel.ieditableobject(v=vs.100).aspx
Reply
Replies
aviade

May 10, 2013 at 9:10 PM

Sounds good, thanks for the link.


Reply

Wahalay Dalaily May 7, 2013 at 12:28 PM


I need to download the zipfiles but, the pages aren't available anymore. Is it possible to send them via
email?
Reply

aviade

May 10, 2013 at 9:09 PM

I double checked, the files should be publicly availiable, if you still can't download shoot me an email, I
will reply with the source.
Reply

kailas August 26, 2013 at 8:59 AM


Thanks a lot...great concepts
Reply

August 7, 2014 at 6:58 PM


Very Nice!
Reply

L Minh Tun August 19, 2014 at 9:32 PM


This article very helpful ;) Thank you so much...
Reply

http://aviadezra.blogspot.com/2009/08/mvp-mvvm-winforms-data-binding.html

12/13

3/10/2014

Design Codes: MVVM for .NET Winforms MVP-VM (Model View Presenter - View Model) Introduction

Enter your comment...

Comment as:

Publish

Google Account

Preview

Links to this post


Create a Link

Newer Post

Home

Older Post

Subscribe to: Post Comments (Atom)

Awesome Inc. template. Powered by Blogger.

http://aviadezra.blogspot.com/2009/08/mvp-mvvm-winforms-data-binding.html

13/13

Das könnte Ihnen auch gefallen