title: WPF: Binding a ContextMenu to an MVVM Command
body: <p>Let's say I have a Window with a property returning a Command (in fact, it's a UserControl with a Command in a ViewModel class, but let's keep things as simple as possible to reproduce the problem).</p>
  
  <p>The following works:</p>
  
  <pre><code>&lt;Window x:Class="Window1" ... x:Name="myWindow"&gt;
      &lt;Menu&gt;
          &lt;MenuItem Command="{Binding MyCommand, ElementName=myWindow}" Header="Test" /&gt;
      &lt;/Menu&gt;
  &lt;/Window&gt;
  </code></pre>
  
  <p>But the following does not work.</p>
  
  <pre><code>&lt;Window x:Class="Window1" ... x:Name="myWindow"&gt;
      &lt;Grid&gt;
          &lt;Grid.ContextMenu&gt;
              &lt;ContextMenu&gt;
                  &lt;MenuItem Command="{Binding MyCommand, ElementName=myWindow}" Header="Test" /&gt;
              &lt;/ContextMenu&gt;            
          &lt;/Grid.ContextMenu&gt;
      &lt;/Grid&gt;
  &lt;/Window&gt;
  </code></pre>
  
  <p>The error message I get is</p>
  
  <blockquote>
    <p>System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=myWindow'. BindingExpression:Path=MyCommand; DataItem=null; target element is 'MenuItem' (Name=''); target property is 'Command' (type 'ICommand')</p>
  </blockquote>
  
  <p>Why? And how do I fix this? Using the <code>DataContext</code> is not an option, since this problem occurs way down the visual tree where the DataContext already contains the actual data being displayed. I already tried using <code>{RelativeSource FindAncestor, ...}</code> instead, but that yields a similar error message.</p>