title: How to use a ContextMenu UserControl in WPF?
body: <p>I have a user control like this:</p>
  
  <pre><code>&lt;UserControl x:Class="MyApp.UserControls.MyContextMenu"
               xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
               xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
               xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
               xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
               mc:Ignorable="d"
               ContextMenuOpening="OnContextMenuOpening"
               d:DesignHeight="300" d:DesignWidth="300"&gt;
  
      &lt;UserControl.ContextMenu&gt;
          &lt;ContextMenu&gt;
          ...
          &lt;/ContextMenu&gt;
      &lt;/UserControl.ContextMenu&gt;
  &lt;/UserControl&gt;
  </code></pre>
  
  <p>My question is: how do I use that context menu for something like a data grid:</p>
  
  <pre><code>&lt;DataGrid ContextMenu="{usercontrols:MyContextMenu}"
  </code></pre>
  
  <p>Unfortunately that does not work because the specified value is incorrect and expected a <code>ContextMenu</code>.</p>
  
  <p><strong>Note:</strong> I need to reuse my context menu in several places, so I have put it in its own file. Also, I need to be able to listen to <code>OnContextMenuOpening</code> events, because the menu upon opening needs to do some work regarding the menu and the event is not fired for the context menu sadly: <a href="http://connect.microsoft.com/VisualStudio/feedback/details/353112/contextmenu-opening-event-doesnt-fire-properly" rel="noreferrer">http://connect.microsoft.com/VisualStudio/feedback/details/353112/contextmenu-opening-event-doesnt-fire-properly</a></p>
  
  <blockquote>
    <p>"ContextMenu itself is a FrameworkElement derived class, but this
    event will not be raised from the context menu being opened as a
    source. The event is raised from the element that "owns" the context
    menu as a property and is only raised when a user attempts to open a
    context menu in the UI."</p>
  </blockquote>
  
  <p>This event problem is the reason I have put the menu for a user control -- so that the user control can get the event and do the work.</p>
  
  <p><strong>Update:</strong> I tried to have it as a root element and extend the context menu:</p>
  
  <p><img src="https://i.stack.imgur.com/rY70b.png" alt="enter image description here"></p>
  
  <p>And code-behind:</p>
  
  <p><img src="https://i.stack.imgur.com/o1kNt.png" alt="enter image description here"></p>
  
  <p>But I'm getting: <code>ContextMenu cannot have a logical or visual parent</code>.</p>