MVP 模式 WinForms:如何正确更新 UI?
MVP pattern WinForms: How to correctly update UI?
鉴于以下 MVP 设置,您将如何更新 winforms UI?这是我第一次尝试实施 MVP,我相信我一直在关注 "Passive View" MVP 实施。
我真的不希望我的模型引用 Presenter,因为我认为这违背了 MVP 模式的想法,但 Presenter 的目的不就是更新视图吗?显然不希望我的模型更新我的视图。如果我的想法有误,请告诉我!
public class HomePresenter
{
Item item;
Model model
SomeTask()
{
model.AnotherTask(item);
}
}
public class Model
{
public void AnotherTask(Item item)
{
/* SOME COMPLEX LOGIC HERE */
if (item.BoolProperty)
// How do I write "Success" to richtextbox in View
else
// How do I write "Failure to richtextbox in View
}
}
您的 Presenter 应该同步您的视图和模型。视图仅显示数据。模型知道业务逻辑和 "real" 数据,Presenter link 模型数据到您的视图。所以你不会从你的模型访问 Richtextbox。相反,您可以从演示者那里执行此操作。要保持独立,您应该使用接口。因此您无法直接访问 Presenter 或 Model 中的 View 元素。
Create an IView Interface and an IModel Interface. Both of them are
known by your Presenter.
您的示例可能如下所示:
public class HomeView : IHomeView
{
public string Text
{
get {return richtextbox.Text;}
set {richtextbox.Text = value;}
}
}
public class HomePresenter
{
IHomeView view;
IModel model;
HomePresenter(IHomeView view, IModel model)
{
view = view;
model = model;
//Update View
view.Text = model.Text;
}
public void UpdateModel
{
model.Text = view.Text; //Set the Model Property to value from Richtextbox
}
}
public class Model : IModel
{
public string Text {get;set} //Property which represent Data from Source like DB or XML etc.
}
你找到另一个例子here。
鉴于以下 MVP 设置,您将如何更新 winforms UI?这是我第一次尝试实施 MVP,我相信我一直在关注 "Passive View" MVP 实施。
我真的不希望我的模型引用 Presenter,因为我认为这违背了 MVP 模式的想法,但 Presenter 的目的不就是更新视图吗?显然不希望我的模型更新我的视图。如果我的想法有误,请告诉我!
public class HomePresenter
{
Item item;
Model model
SomeTask()
{
model.AnotherTask(item);
}
}
public class Model
{
public void AnotherTask(Item item)
{
/* SOME COMPLEX LOGIC HERE */
if (item.BoolProperty)
// How do I write "Success" to richtextbox in View
else
// How do I write "Failure to richtextbox in View
}
}
您的 Presenter 应该同步您的视图和模型。视图仅显示数据。模型知道业务逻辑和 "real" 数据,Presenter link 模型数据到您的视图。所以你不会从你的模型访问 Richtextbox。相反,您可以从演示者那里执行此操作。要保持独立,您应该使用接口。因此您无法直接访问 Presenter 或 Model 中的 View 元素。
Create an IView Interface and an IModel Interface. Both of them are known by your Presenter.
您的示例可能如下所示:
public class HomeView : IHomeView
{
public string Text
{
get {return richtextbox.Text;}
set {richtextbox.Text = value;}
}
}
public class HomePresenter
{
IHomeView view;
IModel model;
HomePresenter(IHomeView view, IModel model)
{
view = view;
model = model;
//Update View
view.Text = model.Text;
}
public void UpdateModel
{
model.Text = view.Text; //Set the Model Property to value from Richtextbox
}
}
public class Model : IModel
{
public string Text {get;set} //Property which represent Data from Source like DB or XML etc.
}
你找到另一个例子here。