Can I create View and Presenter in different Project in MVP Pattern

432 views Asked by At

I am learning MVP pattern for my current project(Windows Application). I have good work experience in MVVM using it in Silverlight and WPF. In MVVM my view and ViewModel use to be in separate project and using the strong binding of WPF they use to communicate to each other. But in MVP most of the example I see in Internet where View and presenter are in same project.

So my Questions are:- Is there any way that I can create View and Presenter in different Project? I mean View as Windows Application and Presenter as Class Library project.

If yes then, how both my View and Presenter refer each other.

1

There are 1 answers

2
Benjamin Gale On BEST ANSWER

Your presenter should only ever communicate with the view via an interface.

Your presenter and view interfaces can be contained in the class library project which the windows application can reference. Any concrete views you create in the windows application project can implement an appropriate view interface.

The simple example below shows how the classes might interact.

ClassLibrary.dll

public class Presenter {

    // Repository class used to retrieve data
    private IRepository<Item> repository = ...;

    public void View { get; set; }

    public void LoadData() {
        // Retrieve your data from a repository or service
        IEnumerable<Item> items = repository.find(...);
        this.View.DisplayItems(items);
    }
}

public interface IView {
    void DisplayItems(IEnumerable<Item> items);
}

WindowsApplication.dll

public class ConcreteView : IView {

    private Button btn
    private Grid grid;
    private Presenter presenter = new Presenter();        

    public ConcreteView() {
        presenter.View = this;
        btn.Click += (s, a) => presenter.LoadData();
    }

    public void DisplayItems(IEnumerable<Item> items) {
        // enumerate the items and add them to your grid...
    }
}