Reputation: 14902
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')
Upvotes: 2
Views: 1603
Reputation: 1693
Another commonly used solution:
<ContextMenu DataContext="{Binding RelativeSource={RelativeSource Self}, Path=PlacementTarget.DataContext}" />
Upvotes: 1
Reputation: 14902
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...
Upvotes: 7