我有一个基于MVP、WinForms和EntityFramework的应用程序。在一个表单中,我需要验证单元格值,但我不知道如何将DataGridView的Validating事件中的EventArgs传递给我的演示者。
我有这个表格(省略了无关代码):
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获取它们,但这很难看,不是吗?
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;
}