问题
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?
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/7606955/how-implement-usercontrol-in-winforms-mvp-pattern