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

时间:2015-03-31 16:19:14

标签: c# winforms event-handling mvp

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

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

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
    }
}

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

1 个答案:

答案 0 :(得分:2)

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

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

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;
}