繁体   English   中英

MVP并传递CancelEventArgs

[英]MVP and passing CancelEventArgs

我正在使用Model-View-Presenter编写一个简单的输入表单,并且在处理FormClosing事件时遇到了困难。

在处理普通Form时,它会在关闭时触发一个名为FormClosing的事件,如果我认为有必要,可以使用该事件来取消关闭。 在这种情况下,如果输入错误,我想取消关闭表单。 例如:

public interface IView
{
  event EventHandler<CancelEventArgs> Closing;

  string Input { get; set; }
  string ErrorMessage { set; }
}

public class Presenter
{
  private IView view;

  public Presenter(IView view)
  {
    this.view = view;

    // bind to events
    view.Closing += view_Closing;
  }

  private void view_Closing(object sender, CancelEventArgs e)
  {
    e.Cancel = !ValidateInput();
  }

  private bool ValidateInput()
  {
    bool validationSuccessful = true;

    // perform validation on input, set false if validation fails
    return validationSuccessful;
  }
}

我创建了自己的事件处理程序( Closing ),因为我对MVP的理解是,利用System.Windows.Forms中的任何内容都不是一个好主意(例如,如果有一天我将视图更新为WPF)。 因此,在WinForms实现中,我将事件向前传递,如下所示:

public partial class View : IView
{
  public event EventHandler<CancelEventArgs> Closing;

  public string Input { get { return textBoxInput.Text; } set { textBoxInput.Text = value; } }
  public string ErrorMessage { set { errorProvider.SetError(textBoxInput, value) ; } }

  public View()
  {
    InitializeComponent();
  }

  private void View_FormClosing(object sender, FormClosingEventArgs e)
  {
    if (Closing != null)
      Closing(this, new CancelEventArgs(e.Cancel));
  }
}

我发现,即使在我的Presenter中我告诉e.Cancel在验证失败时设置为true,也不会导致表单取消关闭。 我显然在这里做错了,但是我不确定什么是正确的解决方案。

我在另一个StackOverflow问题中对该解决方案进行了试验之后,才找到答案 我需要在View创建一个新的CancelEventArgs ,如下所示:

private void View_FormClosing(object sender, FormClosingEventArgs e)
{
  CancelEventArgs args = new CancelEventArgs();

  if (Closing != null)
    Closing(this, args);

  e.Cancel = args.Cancel;
}

args.Cancel Closing事件后, args.Cancel正确更新,并成功将结果布尔值映射到e.Cancel

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM