创建EventHandler并从另一个类中侦听Event

时间:2017-02-22 10:44:48

标签: c#

我已经创建了下面的事件,并希望在它发生时监听它并在另一个类中执行方法 但是saveEvent总是变为null并且它不会触发 我不知道我错过了什么

这是我的第一堂课有按钮

internal partial class OpenSaveReportWizardForm : Form
{
public event EventHandler saveEvent;
private void saveButton_Click(object sender, EventArgs e)
{
  saveEvent?.Invoke(this, e); 
}
}

这里是我要收听saveEvent的第二堂课

 internal class Database
 {
  public Database()
  { 
        Program._wizardForm.saveEvent += (sender, e) => HandleSaveMethod( );

  }

public void HandleSaveMethod()
  {
   // do something
  }

这是我打开表单的地方

internal  class Program
{
  public static OpenSaveReportWizardForm _wizardForm;
  private static void Main()
  {
  OpenFileCommandHandler();
  }

void OpenFileCommandHandler()
     { 
        _wizardForm = new OpenSaveReportWizardForm( );

        _wizardForm.ShowDialog(); 
     }
 }

1 个答案:

答案 0 :(得分:0)

因为你放置了wizardForm,所以在该事件被清除之后。 你应该写下一个代码:

 internal class Database
 {
    private bool _isDisposed;
    private OpenSaveReportWizardForm _wizardForm;

  public Database()
  {
      _wizardForm = new  OpenSaveReportWizardForm(m_Opening,m_ConnectionProperties,m_ColumnProperties))
      _wizardForm.saveEvent += (sender, e) => HandleSaveMethod( );

  }

public void HandleSaveMethod()
  {
   // do something
  }

  public void Dispose()
  {
    if(_isDisposed)
        return;

    _isDisposed = true;

    _wizardForm.saveEvent -= HandleSaveMethod;
    _wizardForm.Dispose();
  }