title: How do I set the DataContext of a ContextMenu defined in TreeView style
body: <p>I have a TreeView which has its ContextMenu defined within a Style. The MenuItems have commands bound to them but I am having trouble binding these commands. I realise that is because the ContextMenu does not exist in the visual tree, so I have tried using the PlacementTarget object and Tag property which I have seen used in other examples but it is still not working. Any ideas what I'm doing wrong.</p>
  
  <pre><code>&lt;Grid Name="MyGrid" DataContext="{Binding}"&gt;
      &lt;TreeView Name="TreeView"
          ItemsSource="{Binding TreeViewElements}"
          Tag="{Binding DataContext, ElementName=MyGrid}"&gt;
          &lt;TreeView.ItemContainerStyle&gt;
              &lt;Style TargetType="{x:Type TreeViewItem}"&gt;
                  &lt;Setter Property="ContextMenu"&gt;
                      &lt;Setter.Value&gt;
                          &lt;ContextMenu DataContext="{Binding PlacementTarget.Tag, RelativeSource={x:Static RelativeSource.Self}}"&gt;
                              &lt;MenuItem Header="Do Something" 
                                        Command="{Binding DoSomethingCommand}"/&gt;
                          &lt;/ContextMenu&gt;
                      &lt;/Setter.Value&gt;
                  &lt;/Setter&gt;
              &lt;/Style&gt;
          &lt;/TreeView.ItemContainerStyle&gt;
          &lt;TreeView.ItemTemplate&gt;
              &lt;HierarchicalDataTemplate ItemsSource="{Binding SubElements}"&gt;
                  &lt;StackPanel Orientation="Horizontal"&gt;
                      &lt;TextBlock Margin="2" Text="{Binding HeaderText}" &gt;&lt;/TextBlock&gt;
                  &lt;/StackPanel&gt;
              &lt;/HierarchicalDataTemplate&gt;
          &lt;/TreeView.ItemTemplate&gt;
      &lt;/TreeView&gt;
  &lt;/Grid&gt;
  </code></pre>
  
  <p><strong>Update</strong></p>
  
  <p>The answers below are both perfectly valid and correct but after some reflection I realised that I was looking at this problem the wrong way round. I had a look a <a href="http://www.codeproject.com/Articles/26288/Simplifying-the-WPF-TreeView-by-Using-the-ViewMode" rel="nofollow">this article by Josh Smith</a> where he explains that using a ViewModel pattern means you use the TreeView to <strong>show data</strong> and not to <strong>put data</strong>. As a result I was able to treat each item in the TreeView as it's own view model. This meant I could execute any command from my context menu against the specific ViewModel (and navigate up to the parent view model if required using a parent property on my new ViewModel).</p>