title: How to set CommandTarget for MenuItem inside a ContextMenu?
body: <p>(This question is related to <a href="https://stackoverflow.com/questions/607370/wpf-how-do-i-set-the-owner-window-of-a-dialog-shown-by-a-usercontrol">another one</a>, but different enough that I think it warrants placement here.)</p>
  
  <p>Here's a (heavily snipped) <code>Window</code>:</p>
  
  <pre><code>&lt;Window x:Class="Gmd.TimeTracker2.TimeTrackerMainForm"
      xmlns:local="clr-namespace:Gmd.TimeTracker2"
      xmlns:localcommands="clr-namespace:Gmd.TimeTracker2.Commands"
      x:Name="This"
      DataContext="{Binding ElementName=This}"&gt;
      &lt;Window.CommandBindings&gt;
          &lt;CommandBinding Command="localcommands:TaskCommands.ViewTaskProperties" 
                          Executed="HandleViewTaskProperties" 
                          CanExecute="CanViewTaskPropertiesExecute" /&gt;
      &lt;/Window.CommandBindings&gt;
      &lt;DockPanel&gt;
  &lt;!-- snip stuff --&gt;
          &lt;Grid&gt;
              &lt;Grid.RowDefinitions&gt;
                  &lt;RowDefinition /&gt;
                  &lt;RowDefinition Height="Auto" /&gt;
              &lt;/Grid.RowDefinitions&gt;
  &lt;!-- snip more stuff --&gt;
              &lt;Button Content="_Create a new task" Grid.Row="1" x:Name="btnAddTask" Click="HandleNewTaskClick" /&gt;
          &lt;/Grid&gt;
      &lt;/DockPanel&gt;
  &lt;/Window&gt;
  </code></pre>
  
  <p>and here's a (heavily snipped) <code>UserControl</code>:</p>
  
  <pre><code>&lt;UserControl x:Class="Gmd.TimeTracker2.TaskStopwatchControl"
               xmlns:local="clr-namespace:Gmd.TimeTracker2"
               xmlns:localcommands="clr-namespace:Gmd.TimeTracker2.Commands"
               x:Name="This"
               DataContext="{Binding ElementName=This}"&gt;
      &lt;UserControl.ContextMenu&gt;
          &lt;ContextMenu&gt;
              &lt;MenuItem x:Name="mnuProperties" Header="_Properties" Command="{x:Static localcommands:TaskCommands.ViewTaskProperties}" 
                        CommandTarget="What goes here?" /&gt;
          &lt;/ContextMenu&gt;
      &lt;/UserControl.ContextMenu&gt;
      &lt;StackPanel&gt;
          &lt;TextBlock MaxWidth="100" Text="{Binding Task.TaskName, Mode=TwoWay}" TextWrapping="WrapWithOverflow" TextAlignment="Center" /&gt;
          &lt;TextBlock Text="{Binding Path=ElapsedTime}" TextAlignment="Center" /&gt;
          &lt;Button Content="{Binding Path=IsRunning, Converter={StaticResource boolToString}, ConverterParameter='Stop Start'}" Click="HandleStartStopClicked" /&gt;
      &lt;/StackPanel&gt;
  &lt;/UserControl&gt;
  </code></pre>
  
  <p>Through various techniques, a <code>UserControl</code> can be dynamically added to the <code>Window</code>.  Perhaps via the Button in the window.  Perhaps, more problematically, from a persistent backing store when the application is started.  </p>
  
  <p>As can be seen from the xaml, I've decided that it makes sense for me to try to use Commands as a way to handle various operations that the user can perform with <code>Task</code>s.  I'm doing this with the eventual goal of factoring all command logic into a more formally-defined Controller layer, but I'm trying to refactor one step at a time.</p>
  
  <p>The problem that I'm encountering is related to the interaction between the command in the <code>UserControl</code>'s <code>ContextMenu</code> and the command's <code>CanExecute</code>, defined in the Window.  When the application first starts and the saved Tasks are restored into TaskStopwatches on the Window, no actual UI elements are selected.  If I then immediately r-click a <code>UserControl</code> in the <code>Window</code> in an attempt to execute the <code>ViewTaskProperties</code> command, the <code>CanExecute</code> handler never runs and the menu item remains disabled.  If I then click some UI element (e.g., the button) just to give something focus, the <code>CanExecute</code> handlers are run with the <code>CanExecuteRoutedEventArgs</code>'s Source property set to the UI element that has the focus.</p>
  
  <p>In some respect, this behavior seems to be known-- I've learned that menus will route the event through the element that last had focus to avoid always sending the event from the menu item.  What I think I would like, though, is for the source of the event to be the control itself, or the Task that the control is wrapping itself around (but <code>Task</code> isn't an Element, so I don't think it can be a source).</p>
  
  <p>I thought that maybe I was missing the <code>CommandTarget</code> property on the <code>MenuItem</code> in the <code>UserControl</code>, and my first thought was that I wanted the command to come from the UserControl, so naturally I first tried:</p>
  
  <pre><code>&lt;MenuItem x:Name="mnuProperties" 
            Header="_Properties" 
            Command="{x:Static localcommands:TaskCommands.ViewTaskProperties}" 
            CommandTarget="{Binding ElementName=This}" /&gt;
  </code></pre>
  
  <p>This failed as an invalid binding.  I'm not sure why.  Then I thought, "Hmmm, I'm looking up the tree, so maybe what I need is a RelativeSource" and I tried this:</p>
  
  <pre><code>&lt;MenuItem x:Name="mnuProperties" 
            Header="_Properties" 
            Command="{x:Static localcommands:TaskCommands.ViewTaskProperties}" 
            CommandTarget="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:TaskStopwatchControl}}}" /&gt;
  </code></pre>
  
  <p>That also failed, but when I looked at my xaml again, I realized that the <code>ContextMenu</code> is in a property of the UserControl, it's not a child element.  So I guessed (and at this point it was a guess):</p>
  
  <pre><code>&lt;MenuItem x:Name="mnuProperties" 
            Header="_Properties" 
            Command="{x:Static localcommands:TaskCommands.ViewTaskProperties}" 
            CommandTarget="{Binding RelativeSource={x:Static RelativeSource.Self}}" /&gt;
  </code></pre>
  
  <p>And that also failed.</p>
  
  <p>One failed guess-and-check like this is enough to make me back off and realize that I'm missing some sort of fundamental concept here, though.  So what do I do?</p>
  
  <ol>
  <li>Is my understanding re: the role of <code>CommandTarget</code> correct in that this provides a mechanism to modify the source of a command?</li>
  <li>How do I bind from a <code>MenuItem</code> in <code>UserControl.ContextMenu</code> to the owning <code>UserControl</code>?  Or am I doing something wrong simply because I perceive a need to?</li>
  <li><p>Is my desire to have the context of a command set by the element that was clicked to generate the context menu, as opposed to the element that had focus before the context menu, incorrect?  Perhaps I need to write my own command instead of using the <code>RoutedUICommand</code>:</p>
  
  <pre><code>private static RoutedUICommand viewTaskPropertiesCommand = new RoutedUICommand("View a task's details.", "ViewTaskProperties", typeof(TaskCommands));
  public static RoutedUICommand ViewTaskProperties
  {
      get { return viewTaskPropertiesCommand; }
  }
  </code></pre></li>
  <li><p>Is there some deeper fundamental flaw in my design?  This is my first significant WPF project, and I'm doing it on my own time as a learning experience, so I'm definitely not opposed to learning a superior solution architecture.</p></li>
  </ol>