如何在 MVP 中将 EventArgs 从 View 传递给 Presenter?

How to pass EventArgs from View to Presenter in MVP?

我有一个基于 MVP、WinForms 和 EntityFramework 的应用程序。 在一种形式下,我需要验证单元格值,但我不知道将 EventArgs 从 DataGridView 的验证事件传递给我的演示者的正确方法。

我有这个表格(无关代码省略):

public partial class ChargeLinePropertiesForm : Form, IChargeLinePropertiesView
{
    public event Action CellValidating;

    public ChargeLinePropertiesForm()
    {
        InitializeComponent();
        dgBudget.CellValidating += (send, args) => Invoke(CellValidating);
    }

    private void Invoke(Action action)
    {
        if (action != null) action();
    }

    public DataGridView BudgetDataGrid
    {
        get { return dgBudget; }
    }
}

接口:

public interface IChargeLinePropertiesView:IView
{
    event Action CellValidating;
    DataGridView BudgetDataGrid { get; }
}

这位主持人:

public class ChargeLinePropertiesPresenter : BasePresenter<IChargeLinePropertiesView, ArgumentClass>
{
    public ChargeLinePropertiesPresenter(IApplicationController controller, IChargeLinePropertiesView view)
        : base(controller, view)
    {
        View.CellValidating += View_CellValidating;
    }

    void View_CellValidating()
    {
        //I need to validate cell here based on dgBudget.CellValidating EventArgs
        //but how to pass it here from View?

        //typeof(e) == DataGridViewCellValidatingEventArgs
        //pseudoCode mode on
        if (e.FormattedValue.ToString() == "Bad")
        {
            View.BudgetDataGrid.Rows[e.RowIndex].ErrorText =
                "Bad Value";
            e.Cancel = true;
        }
        //pseudoCode mode off
    }
}

是的,我可以通过界面公开一个 属性 并在视图中将我的 EventArgs 设置为此 属性 以从 Presenter 获取它们,但这很丑陋,不是吗?

public interface IChargeLinePropertiesView:IView
{
    event Action CellValidating;
    // etc..
}

使用Action是这里的问题,它是错误的委托类型。它不允许传递任何参数。解决此问题的方法不止一种,例如,您可以使用 Action<CancelEventArgs>。但合乎逻辑的选择是使用与验证事件相同的委托类型:

event CancelEventHandler CellValidating;

现在很容易了。在您的表单中:

public event CancelEventHandler CellValidating;

public ChargeLinePropertiesForm() {
    InitializeComponent();
    dgBudget.CellValidating += (sender, cea) => {
        var handler = CellValidating;
        if (handler != null) handler(sender, cea);
    };
}

在您的演示者中:

void View_CellValidating(object sender, CancelEventArgs e)
{
   //...
   if (nothappy) e.Cancel = true;
}