开发者

how Implement usercontrol in winforms mvp pattern?

I 开发者_开发知识库want to Implement MVP pattern. I have a user control that has some Textboxes and when I put it in form I call a method from usercontrol and fill textboxes. But in mvp pattern I don't know how I can access to usercontrol1.fill(). Do you have an example that could help me?


Here is an example implementation of the pattern. The Presenter only knows about the interface having a show method. The Presenter calls it, but the only the form (aka View) implements how the form should be displayed.

public interface IMyFormView {
    void Show();
}

public class MyForm : IMyFormView {

    public MyForm() {
        var presenter = new MyFormPresenter(this);
        presenter.Init();
    }

    public void Show() {
        usercontrol1.fill();
    }
}

public class MyFormPresenter
{
    private IMyView _view;
    public MyFormPresenter(IMyView view) {
        _view = view;
    }

    public void Init() {
        _view.Show();
    }
}

If you need to pass data into the view, then you can pass a view model through the Show-method or set custom Properties on the view.


If your user control is placed into a form, and assuming that the form is a view in your project, then it is this view who has the responsibility of accessing the user control. You should not access any method of the user control directly from the presenter. In fact the presenter should not have any knowledge of the existence of those methods or even the user control. The presenter only knows of the existence of a view who implements an existing interface for that view. So, your view (the form) is the one that will know and call the method of this usercontrol. To pass values from the presenter to fill the user control placed in your form, the interface that is implemented by your view should expose a public property with the set method, (and a get method if you are planning to also read those values). As your view is implementing this interface, in the implementation of the set method of this property, you can there call any method of the user control, as the user control is included in your form and your form knows of the existence of the user control and its methods. You shouldn't have any problem accessing it from there.

In the same way, if you need to read the values from the user control, this should be done in the view, on the get implementation of this property. The presenter just reads the property using the get method defined in the interface, and the view will know how to access the values and return them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜