【问题标题】:How to pass EventArgs from View to Presenter in MVP?如何在 MVP 中将 EventArgs 从 View 传递给 Presenter?
【发布时间】:2015-03-31 16:19:14
【问题描述】:

我有一个基于 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 获取它们,但这很丑,不是吗?

【问题讨论】:

    标签: c# winforms event-handling mvp


    【解决方案1】:
    public interface IChargeLinePropertiesView:IView
    {
        event Action CellValidating;
        // etc..
    }
    

    使用Action 是这里的问题,它是错误的委托类型。它不允许传递任何参数。解决此问题的方法不止一种,例如,您可以使用Action&lt;CancelEventArgs&gt;。但合乎逻辑的选择是使用与 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-02
      • 2017-08-16
      • 1970-01-01
      • 1970-01-01
      • 2016-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多