MVVM is most commonly used with WPF because it is perfectly suited for it. But what about Windows Forms? Is there an established and commonly used approach / design pattern like this for Windows Forms too? One that works explicitly well with Windows Forms? Is there a book or an article that describes this well? Maybe MVP or MVC based?
Yes you can, both Windows Forms within a WPF application, and WPF controls within Windows Forms.
MVVM is really just another name for "Presentation Model" which has been around for longer than MVVM has been named. Plus, it is not true that WinForms can't do data binding. It is just a different mechanism. @BrianGenisio, MVVM is indeed a variant of PM, but it's not the same.
MVVM is the lingua franca of WPF developers because it is well suited to the WPF platform, and WPF was designed to make it easy to build applications using the MVVM pattern (amongst others).
I have tried MVP and it seems to work great with windows forms too. This book has an example of windows forms with MVP pattern (sample payroll application). The application is not that complex but will give you an idea about how to go about creating it.
Agile Principles, Patterns, and Practices in C#...
You can get the source code at Source Code
There are two variations of the MVP pattern (a) Passive view and (b) supervising controller
For complex databinding scenarios I prefer to go with the Supervising controller pattern. In supervising controller pattern the databinding responsibility rest with the view. So,for treeview/datagrid this should be in the respective views, only view agnostic logic should moved on to the presenter.
I'll recommend having a look at the following MVP framework MVC# - An MVP framework
Don't go by the name (it's an MVP framework).
Simple winforms MVP video Winforms - MVP
An example of dealing with dropdown list MVP - DropDownList
Below is the code snippet.... not tested, directly keyed in from thought....
public interface IYourView
{
void BindTree(Model model);
}
public class YourView : System.Windows.Forms, IYourView
{
private Presenter presenter;
public YourView()
{
presenter = new YourPresenter(this);
}
public override OnLoad()
{
presenter.OnLoad();
}
public void BindTree(Model model)
{
// Binding logic goes here....
}
}
public class YourPresenter
{
private IYourView view;
public YourPresenter(IYourView view)
{
this.view = view;
}
public void OnLoad()
{
// Get data from service.... or whatever soruce
Model model = service.GetData(...);
view.BindTree(model);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With