簡體   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