如何为所有SmartPart制作自定义事件?

时间:2013-09-02 06:50:25

标签: event-handling compact-framework mvp opennetcf scsf

有C#Project(.NET CF)使用OpenNETCF.IOC。(UI)库。

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

重构后: 基本表格现在是容器形式。所有后代形式现在都是SmartParts。 我现在应该如何将自定义事件从容器表单提升到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;
     ...
 }

1 个答案:

答案 0 :(得分:2)

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

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 
    }
}