1

有使用 OpenNETCF.IOC.(UI) 库的 C# 项目 (.NET CF)。

实际情况:在基本表单中处理 OnKeyDown 事件并且可以引发自定义事件(例如,如果用户按下了 ESC 按钮)。此事件可以以后代形式处理。

重构后:Base Form 现在是容器表单。所有后代形式现在都是 SmartPart。我现在应该如何将自定义事件从容器表单提升到 SmartParts?

// Base form
private void BaseForm_KeyDown(object sender, KeyEventArgs e)
{
   // Handle ESC button
   if (e.KeyCode == Keys.Escape || e.KeyValue == SomeOtherESCCode)
   {
       this.ButtonESCClicked(sender, new EventArgs());
   }
 }

 // Descendant form
 private void frmMyForm_ButtonESCClicked(object sender, EventArgs e)
 {
     this.AutoValidate = AutoValidate.Disable;
     ...
 }
4

1 回答 1

2

我不确定我是否完全理解这个问题,但我会尽力回答。如果要从子类中引发事件,但该事件是在基类中定义的,则应在基类中使用“帮助器”方法:

public abstract ParentClass : Smartpart
{
    public event EventHandler MyEvent;

    protected void RaiseMyEvent(EventArgs e)
    {
        var handler = MyEvent;
        if(handler != null) handler(this, e);
    }
}

public ChildClass : ParentClass
{
   void Foo()
   {
       // rais an event defined in a parent
       RaiseMyEvent(EventArgs.Empty);
   }
}

如果您尝试另一种方式,让父母通知孩子,那么它更像是这样:

public abstract ParentClass : Smartpart
{
    protected virtual void OnMyEvent(EventArgs e) { } 

   void Foo()
   {
       // something happened, notify any child that wishes to know
       OnMyEvent(EventArgs.Empty);

       // you could optionally raise an event here so others could subscribe, too
   }
}

public ChildClass : ParentClass
{
    protected override void OnMyEvent(EventArgs e)
    {
        // this will get called by the parent/base class 
    }
}
于 2013-09-02T18:57:47.820 回答