title: WPF ContextMenu with ItemsSource - how to bind to Command in each item?
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/898852/specify-command-for-menuitem-in-a-datatemplate">Specify Command for MenuItem in a DataTemplate</a>  </p>
  </blockquote>
  
  
  
  <p>I have a collection of objects (viewmodels) that represent menu items. Each of them have a command that I would like to execute when a MenuItem is clicked.</p>
  
  <p>If I wanted to do the menu statically, I do it like this:</p>
  
  <pre><code>&lt;ContextMenu&gt;
      &lt;MenuItem Header="{Binding Text1}" Command={Binding Command1}&gt;
      &lt;MenuItem Header="{Binding Text2}" Command={Binding Command2}&gt;
  &lt;/ContextMenu&gt;
  </code></pre>
  
  <p>but when I don't know the items in advance (they come from a collection), I need to assign ContextMenu.ItemsSource - and put a text into a ItemTemplate.</p>
  
  <pre><code>&lt;ContextMenu ItemsSource="{Binding MyMenuItems}"&gt;
      &lt;ContextMenu.ItemTemplate&gt;
          &lt;DataTemplate&gt;
              &lt;TextBlock Text="{Binding Text2}" /&gt; &lt;!-- But where to put Command binding? TextBlock.Command makes no sense, and we have no access to MenuItem! --&gt;
          &lt;/DataTemplate&gt;
      &lt;/ContextMenu.ItemTemplate&gt;
  &lt;/ContextMenu&gt;
  </code></pre>
  
  <p>This way, however, I have no place to bind a Command to - because I can't get the MenuItem for every row!</p>
  
  <p>Any advice, please? Thank you, guys!</p>