title: How to raise ContextMenuOpening event when opening context menu programmatically
body: <p>When I open a context menu with <code>&lt;control&gt;.ContextMenu.IsOpen = true</code>, the context menu becomes visible but neither the opening or closing events are triggered.</p>
  
  <p>How can I make sure the <code>ContextMenuOpening</code> and <code>ContextMenuClosing</code> events are raised when I open a context menu programmatically?</p>
  
  <hr>
  
  <h2>Demo:</h2>
  
  <p>Look at the following XAML</p>
  
  <pre><code>&lt;Button Name="ContextMenuButton" 
          Content="Click me!" 
          Click="ContextMenuButton_Click" 
          ContextMenuOpening="ContextMenuButton_OnContextMenuOpening"
          ContextMenuClosing="ContextMenuButton_OnContextMenuClosing"&gt;
      &lt;Button.ContextMenu&gt;
          &lt;ContextMenu&gt;
              &lt;MenuItem Header="First element" /&gt;
              &lt;MenuItem Header="Second element" /&gt;
          &lt;/ContextMenu&gt;
      &lt;/Button.ContextMenu&gt;
  &lt;/Button&gt;
  </code></pre>
  
  <p>And the following code-behind</p>
  
  <pre><code>public MainWindow() // Constructor
  {
      InitializeComponent();
      ContextMenuButton.ContextMenuOpening += (sender, args) =&gt; Debug.Print("Opening #2");
      ContextMenuButton.ContextMenuClosing += (sender, args) =&gt; Debug.Print("Closing #2");
  }
  
  private void ContextMenuButton_Click(object sender, RoutedEventArgs e)
  {
      Button button = (sender as Button);
      button.ContextMenu.IsOpen = true; // How should I open the ContextMenu?
  }
  
  private void ContextMenuButton_OnContextMenuOpening(object sender, ContextMenuEventArgs e)
  {
      Debug.Print("Opening #1");
  }
  
  private void ContextMenuButton_OnContextMenuClosing(object sender, ContextMenuEventArgs e)
  {
      Debug.Print("Closing #1");
  }
  </code></pre>
  
  <h2>Behavior when right-clicking on the button:</h2>
  
  <p>Context menu is opening.</p>
  
  <p>Output is: </p>
  
  <pre><code>Opening #1
  Opening #2
  Closing #1
  Closing #2
  </code></pre>
  
  <h2>Behavior when left-clicking on the button:</h2>
  
  <p>Context menu is opening.</p>
  
  <p>Output is: </p>
  
  <pre><code>&lt;Nothing&gt;
  </code></pre>