title: Checking if a RoutedEvent has any handlers
body: <p>I've got a custom Button class, that always performs the same action when it gets clicked (opening a specific window). I'm adding a Click event that can be assigned in the button's XAML, like a regular button.</p>
  
  <p>When it gets clicked, I want to execute the Click event handler if one has been assigned, otherwise I want to execute the default action. The problem is that there's apparently no way to check if any handlers have been added to an event.</p>
  
  <p>I thought a null check on the event would do it:</p>
  
  <pre><code>if (Click == null) 
  { 
      DefaultClickAction(); 
  } 
  else 
  { 
      RaiseEvent(new RoutedEventArgs(ClickEvent, this));;
  }
  </code></pre>
  
  <p>...but that doesn't compile. The compiler tells me that I can't do anything other than += or -= to an event outside of the defining class, event though I'm trying to do this check INSIDE the defining class.</p>
  
  <p>I've implemented the correct behavior myself, but it's ugly and verbose and I can't believe there isn't a built-in way to do this. I must be missing something.</p>
  
  <p>Here's the relevant code:</p>
  
  <pre><code>public class MyButtonClass : Control
  {
      //...
  
      public static readonly RoutedEvent ClickEvent =
          EventManager.RegisterRoutedEvent("Click",
                                           RoutingStrategy.Bubble,
                                           typeof(RoutedEventHandler),
                                           typeof(MyButtonClass));
  
      public event RoutedEventHandler Click
      {
          add { ClickHandlerCount++; AddHandler(ClickEvent, value); }
          remove { ClickHandlerCount--; RemoveHandler(ClickEvent, value); }
      }
  
      private int ClickHandlerCount = 0;
  
      private Boolean ClickHandlerExists
      {
          get { return ClickHandlerCount &gt; 0; }
      }
  
      //...
  }
  </code></pre>