How do I add a command to items in dynamically generated ContextMenu
<p>I have a context menu that is being populated from an ObservableCollection. I want the user to be able to click on any of those items, then a method is called passing the clicked item's text as a parameter.</p>

<p>I've started by following the answer to <a href="https://stackoverflow.com/questions/24875966/databinding-a-command-to-context-menu-with-an-observable-collection">this question</a>. However, I'm getting an error in my console output and my method is not being called.</p>

<blockquote>
  <p>System.Windows.Data Error: 40 : BindingExpression path error: 'FunctionToCall' property not found on 'object' ''MenuItem' (Name='myMenu')'. BindingExpression:Path=FunctionToCall; DataItem='MenuItem' (Name='myMenu'); target element is 'MenuItem' (Name=''); target property is 'Command' (type 'ICommand')</p>
</blockquote>

<p>here is my xaml</p>

<pre class="lang-xml prettyprint-override"><code>            &lt;MenuItem Name="myMenu" Header="display text" ItemsSource="{Binding}" &gt;
                &lt;MenuItem.ItemContainerStyle&gt;
                    &lt;Style TargetType="MenuItem"&gt;
                        &lt;Setter Property="Command" Value="{Binding FunctionToCall, RelativeSource={RelativeSource AncestorType=MenuItem}}"/&gt;
                        &lt;Setter Property="CommandParameter" Value="{Binding}"/&gt;
                    &lt;/Style&gt;
                &lt;/MenuItem.ItemContainerStyle&gt;
            &lt;/MenuItem&gt;
</code></pre>

<p>And my view model code
</p>

<pre><code>    RelayCommand _command;
    public ICommand FunctionToCall
    {
        get
        {
            if (_command == null)
            {

                _command = new RelayCommand(p =&gt; this.InnerMethod(p));
            }
            return _command ;
        }
    }
    public void InnerMethod(object parameter)
    {
        ....
</code></pre>

<p>The other answer suggests playing around with adding one or two DataContexts to the Binding, I've tried this and I still get the same error although it says DataContext property cannot be found instead of FunctionToCall. </p>

<p>I found the definition of RelayCommand <a href="http://snipplr.com/view/13642/" rel="nofollow noreferrer">here</a>. </p>