我正在尝试实现 MVP 模式并且我在事件处理程序方面遇到了一些问题。最初我在部分类中声明了这一点。因为它包含逻辑我假设它应该被移动到演示者中?
不过,当我将 InvokeRequired/invoke 移到 Presenter 时,它显然会产生错误。因此,除了将整个方法留在视图中之外,我想出的唯一其他选择是将事件处理程序留在视图中,因此 InvokeRequired 等不会有任何问题,而是移动 EventHandler 的主体,即动作委托,进入演示者。我不知道这样的方法调用将如何工作,尽管我使用 DI atm 在 View -> Presenter 之间进行通信,但不确定如何获取 Presenter -> View。
public void CompletionReportNotifier(object sender, VerificationStatusEventArgs e)
{
Action action = () =>
{
//Display messages depending on whether it was canceled or not.
if (e.CarriedOutToCompletion == true)
{
string logMessage = string.Format("The data verification operation has been completed and {0} errors were found. Please view the error log for additional information.", inputs.NumberOfErrorsFound.ToString());
_view.UpdateLog(logMessage);
}
else
{
_view.UpdateLog("The data verification has failed. Please view the error log for additional information.");
}
//...
};
if (InvokeRequired)
Invoke(action);
else
action();
}
根据ItsMatt的回复编辑
演示者代码:
public void CompletionReportNotifier(object sender, VerificationStatusEventArgs e)
{
_view.PermanentCsvFileVerificationCancellation = null;
string logMessage;
bool inputsVisible = false;
//Display messages depending on whether it was canceled or not.
if (e.CarriedOutToCompletion == true)
{
logMessage = string.Format("The data verification operation has been completed and {0} errors were found. Please view the error log for additional information.", inputs.NumberOfErrorsFound.ToString());
}
else
{
logMessage = "The data verification has failed. Please view the error log for additional information.";
}
//Assign values to parameters depending on if it failed or errors were encountered.
if (e.CarriedOutToCompletion != true || inputs.NumberOfErrorsFound > 0)
{
inputsVisible = true;
_view.VerificationCompleted = false;
}
else
{
_view.VerificationCompleted = true;
}
_view.UIUpdate(logMessage, inputsVisible);
}
查看代码:
public void UIUpdate(string logMessage, bool inputsVisible)
{
Action action = () =>
{
UpdateLog(logMessage);
AccessToCsvFileVerificationInputs(inputsVisible);
btnDataVerification.Text = "Verify Data";
DisplayBusyMouseCursor(false);
VerifyingData = false;
};
if (InvokeRequired)
Invoke(action);
else
action();
}