title: WPF: How do I get the ContextMenu for a MenuItem in a submenu?
body: <p>I have a ContextMenu defined in the following way:</p>
  
  <pre><code>&lt;ContextMenu&gt;
      &lt;MenuItem Header="Add to"&gt;
          &lt;MenuItem Header="Test1" Click="ItemClicked" /&gt;
          &lt;MenuItem Header="Test2" Click="ItemClicked" /&gt;
      &lt;/MenuItem&gt;
      &lt;MenuItem Header="Remove from All" /&gt;
  &lt;/ContextMenu&gt;
  </code></pre>
  
  <p><strong>But in the ItemClicked function how would I get a reference to the parent ContextMenu??</strong></p>
  
  <p>For the first level items (e.g. "Remove from All") I can do something like the following:</p>
  
  <pre><code>var mi = sender as MenuItem;
  if (mi != null)
  {
      var cm = mi.Parent as ContextMenu;
      if (cm != null)
      {
          var lb = cm.PlacementTarget as ListBox;
          if (lb != null)
          {
              // Do Stuff
          }
      }
  }
  </code></pre>
  
  <p>But this doesn't work for submenu MenuItems because their Parent is null...</p>