1

OpenNETCF.IOC.(UI) ライブラリを使用する C# プロジェクト (.NET CF) があります。

実際の状況: ベース フォームでは 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;
     ...
 }
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 に答える