3

我正在尝试使用 MVP,我注意到我的视图必须知道模型,我认为这不应该发生在 MVP 中。

这是示例:

public partial class TestForm : Form, ITestView
{
    public void LoadList(IEnumerable<AppSignature> data)
    {
        testPresenterBindingSource.DataSource = data;
    }
}

public interface ITestView
{
    event EventHandler<EventArgs> Load;
    void LoadList(IEnumerable<AppSignature> data);
}

public class TestPresenter
{
   private ITestView view;

   public TestPresenter(ITestView view)
   {  
       this.view = view;
       view.Load += View_Load;
   } 

   private void View_Load(object sender, EventArgs e)
   {
       var data = // get from model
       view.LoadList(data);
   }
}

问题是在TestForm 中我需要参考AppSignature。在我看到的所有教程中,都有一些简单的例子,比如 public void LoadList(IEnumerable<String> data)不需要参考模型。但是 ie DataGridView 是如何发布当前行数据的呢?

4

3 回答 3

2

The View may have knowledge of Model as long as the interaction is limited to data binding only. i.e. View should not try to manipulate Model directly. View will always redirect user input to Presenter and Presenter will take care of further actions. If any action performed by Presenter results in a change in state of Model, Model will notify View via data binding. Model will be completely unaware of existence of View.

于 2012-10-22T16:55:53.227 回答
2

您的表单是一个视图,它不是一个演示者。因此它应该实现接口ITestView

public interface ITestView
{
    event EventHandler Load;
    void LoadList(IEnumerable<AppSignatureDto> data);
}

您的 Presenter 是订阅视图事件并使用视图属性来读取和更新视图的人:

public class TestPresenter
{
   private ITestView view;

   public TestPresenter(ITestView view)
   {  
       this.view = view;
       view.Load += View_Load;
   } 

   private void View_Load(object sender, EventArgs e)
   {
       List<AppSignature> signatures = // get from model
       List<AppSignatureDto> signatureDtos = // map domain class to dto
       view.LoadList(signatureDtos);
   }
}

正如我已经说过的,你的形式是一个视图,它对演示者和模型一无所知:

public partial class TestForm : Form, ITestView
{
    public event EventHandler Load;    

    private void ButtonLoad_Click(object sender, EventArgs e)
    {
        if (Load != null)
            Load(this, EventArgs.Empty);
    }

    public void LoadList(IEnumerable<AppSignatureDto> data)
    {
        // populate grid view here
    }
} 

如何处理对域类的引用?通常我只提供查看简单数据(字符串、整数、日期等),或者我创建传递给视图的数据传输对象(您可以将它们命名为 FooView、FooDto 等)。您可以使用AtoMapper之类的东西轻松映射它们:

List<AppSignatureDto> signatureDtos = 
      Mapper.Map<List<AppSignature>, List<AppSignatureDto>>(signatures);
于 2012-10-22T16:53:04.880 回答
0

可以在 Presenter 中获取 DataSource 并设置它的 DataSource 吗?例如演示者代码:

Public void LoadData()
{
    _view.Data.DataSource = Business.GetData().ToList();
}

表格代码:

Public BindingSource Data
{
    get
    {
        return this.bsData;
    }
}

多亏了这一点,我不需要添加对视图的任何引用,但我没有在任何其他来源中看到该解决方案。

于 2013-11-19T00:08:55.897 回答