开发者

Is it possible for a class to respond when a calling class subscribes to one of its events

I have a windows form with a button on it and I only want that button to be visible, if the form that calls it, has subscribed to one of the forms custom events.

I know I can check whether myEvent == null, but what if the event is subscribed to after the form has been loaded?

Is this possible?

(Perhaps 开发者_JS百科just a timer on the form, continually checking whether the event is null?? (sounds messy though)


If it's a custom event, you can put the overrides on where the client subscribes / unsubscribes:

   private EventHandler _customEventDelegate;

   public event EventHandler MyCustomEvent
   {
      add
      {
          bool wasNull = (_customEventDelegate == null);
          _customEventDelegate += value;
          if(wasNull)
          {
              this.ChangeButtonVisibility(true);
          }
      }
      remove
      {
          _customEventDelegate -= value;
          if(_customEventDelegate == null)
          {
             this.ChangeButtonVisibility(false);
          }
      }
   }


Just like properties events have associated methods as well so:

public event EventHandler MyEvent {
    add {
        // do something
    }
    remove {
        // do something 
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜