.

most basic MVP structure (non-generic)

Bitlink MVP example.cs

this is just a very simple MVP structure (non-generic).

You have an IPresenter interface:

public interface IPresenter
{
    IView Form { get; set; }
    event EventHandler OnViewInitialized;
    event EventHandler OnViewLoaded;
    void ModelNameChanged(string p);
}

You have an IView interface:

public interface IView
{
    IPresenter Presenter { get; set; }
    event EventHandler OnUserControlLoaded;
    void ShowOnView(IModel model);
}

You have an IModel interface:

public interface IModel : INotifyPropertyChanged
{
    string name { get; set; }
}

You have a concrete Model class:

public class Model : IModel
{
    public Model()
    {
    }

    public string name { get; set; }
    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

You have a concrete View form:

public partial class Form1 : Form, IView
{
    //public MyPresenter Presenter;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    public IPresenter Presenter { get; set; }
    public event EventHandler OnUserControlLoaded;

    public void ShowOnView(IModel model)
    {
        button1.Text = model.name;
        textBox1.Text = model.name;
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        Presenter.ModelNameChanged(textBox1.Text);
    }

}

You have a concrete Presenter class:

public class Presenter : IPresenter
{
    private readonly IModel ViewModel;

    public Presenter(IModel ViewModel, IView form)
    {
        this.ViewModel = ViewModel;
        this.Form = form;
        form.Presenter = this;
        if (OnViewInitialized != null)
            OnViewInitialized(this, null);
        if (OnViewLoaded != null)
            OnViewLoaded(this, null);
        form.ShowOnView(ViewModel);
    }

    public IView Form { get; set; }
    public event EventHandler OnViewInitialized;
    public event EventHandler OnViewLoaded;

    public void ModelNameChanged(string p)
    {
        ViewModel.name = p;
        Form.ShowOnView(ViewModel);
    }
}

And you wire it up as follow:

[STAThread]
private static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Form1 mainForm = new Form1();
    Model model = new Model();
    model.name = "pietman";
    Presenter cpr = new Presenter(model, mainForm);

    Application.Run(mainForm);
}

in the end I ended up converting it to a generic pattern
– download here: Generic MVP example

What's your thoughts on this?

*

Protected by WP Anti Spam