title: How to reference right-clicked object in WPF Context Menu item click event handler?
body: <p>In WPF application there is a <code>Grid</code> with a number of objects (they are derived from a custom control). I want to perform some actions on each of them using context menu:</p>
  
  <pre><code>   &lt;Grid.ContextMenu&gt;
       &lt;ContextMenu&gt;
         &lt;MenuItem  Name="EditStatusCm" Header="Change status" Click="EditStatusCm_Click"/&gt;
       &lt;/ContextMenu&gt;                   
     &lt;/Grid.ContextMenu&gt; 
  </code></pre>
  
  <p>But in the event handler I cannot get know which of the objects was right-clicked:</p>
  
  <pre><code>    private void EditStatusCm_Click(object sender, RoutedEventArgs e)
      {
          MyCustControl SCurrent = new MyCustControl();
          MenuItem menu = sender as MenuItem;
          SCurrent = menu.DataContext as MyCustControl; // here I get a run-time error
          SCurrent.Status = MyCustControl.Status.Sixth;
      }
  </code></pre>
  
  <p>On that commented line Debugger says: <strong><em>Object reference not set to an instance of an object.</em></strong></p>
  
  <p>Please help, what is wrong in my code?</p>
  
  <p><strong>Edited (added):</strong></p>
  
  <p>I tried to do the same, using <strong>Command</strong> approach:</p>
  
  <p>I declared a <code>DataCommands</code> Class with <code>RoutedUICommand Requery</code> and then used <code>Window.CommandBindings</code></p>
  
  <pre><code>&lt;Window.CommandBindings&gt;
    &lt;CommandBinding Command="MyNamespace:DataCommands.Requery" Executed="RequeryCommand_Executed"&gt;&lt;/CommandBinding&gt;
  &lt;/Window.CommandBindings&gt;
  </code></pre>
  
  <p>XAML of MenuItem now looks like:</p>
  
  <pre><code>&lt;Grid.ContextMenu&gt;
   &lt;ContextMenu&gt;
    &lt;MenuItem  Name="EditStatusCm" Header="Change status"  Command="MyNamespace:DataCommands.Requery"/&gt;
   &lt;/ContextMenu&gt;                   
  &lt;/Grid.ContextMenu&gt;
  </code></pre>
  
  <p>And event handler looks like:</p>
  
  <pre><code>    private void RequeryCommand_Executed(object sender, ExecutedRoutedEventArgs e)
      {
          IInputElement parent = (IInputElement)LogicalTreeHelper.GetParent((DependencyObject)sender);
          MyCustControl SCurrent = new MyCustControl();
          SCurrent = (MuCustControl)parent;
          string str = SCurrent.Name.ToString();// here I get the same error
          MessageBox.Show(str);
      }
  </code></pre>
  
  <p>But debugger shows the same run-time error: <strong><em>Object reference not set to an instance of an object.</em></strong></p>
  
  <p>What is missing in my both approaches?</p>
  
  <p>How I should reference right-clicked object in WPF Context Menu item click event handler?</p>