0

I'm trying to use the MVP (Passive View) pattern in a Winforms application. As far as I understand, in the Passive View implementation of MVP, the View doesn't know about the Presenter, so I need to communicate with it somehow. I'm using events for this. However, I'm having a problem: when the TextChanged event is fired in the View, the FileName field has already been changed by the time the OnSetName() method is called in the Presenter. This causes issues because I thought that the View in MVP would remain completely passive. For example, I want to have logic in the Presenter to avoid accepting certain names, but when I reach the OnSetName() method, it's already too late because the name has already been set.

public partial class Form1 : IPassiveView
{

    public Form1()
    {
        InitializeComponent();
    }

    public string FileName
    {
        get => textEdit1.Text;
        set => textEdit1.Text = value;
    }

    public event EventHandler<string> NameChanged;

    private void textEdit1_EditValueChanged(object sender, EventArgs e)
    {
        OnNameChanged(FileName);
    }

    protected virtual void OnNameChanged(string e)
    {
        NameChanged?.Invoke(this, e);
    }
}

public interface IPassiveView
{
    string FileName { get; set; }

    event EventHandler<string> NameChanged;
}

public sealed class Presenter
{
    private readonly IPassiveView _view;
    public Presenter(IPassiveView view)
    {
        _view = view;
        _view.NameChanged += (sender, s) => OnSetName(s);
    }

    public void OnSetName(string name)
    {
        _view.FileName = name;
    }
}
Vahid
  • 5,144
  • 13
  • 70
  • 146
  • You have a recursive circle implementation. When the text value is changed of `TextEdit1` the event is fired. This event updates the `FileName` property. When this propery is set, is sets the `Text` of `TextEdit1`. This will fire the event again. See what is happening? What is the purpose of setting the 'TextEdit.Text'? What do you want to accomplish? – Stefan Sep 19 '19 at 07:32
  • @Stefan I know! And to my surprise it does not actually fire in a loop. My problem is not that though. My question is am I doing the Passive-View implementation of MVP correctly? – Vahid Sep 19 '19 at 07:34

0 Answers0