1
votes

I have a ContextMenu in a TreeView

UserControl (DataContext=ViewModel)
    |
    |
    ---- TreeView (ItemSource=MyItems)
           |
           |
           ----- Items (ItemSource=MyChildrenItems)
                   |
                   |
                   ----- ContextMenu

I want to bind the Command of the ContextMenuItem to a RelayCommand in the ViewModel, I tried all kinds of RelativeSource bindings, but nothing seems to work...

How should I configure the RelativeSource binding?

<ContextMenu>
    <MenuItem
        Header="Bla"
        Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=TreeView}, Path=DataContext.MyRelayCommand}" />

I get binding errors like

Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.TreeView', AncestorLevel='1''. BindingExpression:Path=DataContext.ExcludeSeasonCommand; DataItem=null; target element is 'MenuItem' (Name=''); target property is 'Command' (type 'ICommand')

2

2 Answers

2
votes

Finally, after many many many google searches I ran into the solution

<MenuItem
    Header="Exclude season"
    Command="{Binding DataContext.MyRelayCommand, Source={x:Reference _myTreeView}}" />

Because the HierarchicalDataTemplate does not appear in the visual tree, there is not "relative" source...

I hope this helps somebody else who's pulling his/her hair out...

1
votes

Another commonly used solution:

<ContextMenu DataContext="{Binding RelativeSource={RelativeSource Self}, Path=PlacementTarget.DataContext}" />