Thursday, August 25, 2016

Callback function

假設準備由 A 跳去 B, 而 B  去到某個情況下, 要 番去 執行 A 既野.

1) 如果 B 係一個 UserControl, 嚴格黎講, 唔算係 call back.  可以用 event 攪掂.

    (a) 在 B 設定一個  event
            public event EventHandler EventName>;

        By default,  個 event 既 parameter 係 EventArgs, 如果想用其他 type, 可以設定
            public event EventHandler<string>  EventName;

       咁樣, 個 event 就會有個 string type 既 parameter

    (b)  當 B 雖要 通知 A 時, 就可以 check 下個 Event 有無設定 handler, 有就 call.

       例如用番 default 既, 而你又無 parameter 要 pass, 可以咁 call:

          if (EventName != null) EventName(this, EventArgs.Empty);

    (c) 而 A 當然要在 B 既 event 設定一個 handler 比佢, 而設定既方法同其他 event 無分別.


2) 如果 B 係一個 Window, 就真係可以用 call back function 了.

    (a) 首先, 在 B 設定一個預備 call back 既 function signature, 再 設定一個 variable

             public delegate void DelActionHandler(string data);
             public event DelActionHandler actionHandler;
           
    (b) 當 B 雖要 通知 A 時, 就可以 check 下個 Event 有無設定 handler, 有就 call.

           if (actionHandler != null) actionHandler("data");

    (c) 而 A 當然要先設定一個配合 DelActionHandler 既 function, 然後就將佢加入去

          B.actionHandler += new DelActionHandler(this.action);

          private void action(string data) {...}