I have a TreeView with ContextMenu, and inside that menu I want to bind to a command on VIewModel
<TreeView x:Name="treeView"
ItemTemplate="{StaticResource ItemTemplate}"
ItemsSource="{Binding View}">
<TreeView.ContextMenu>
<ContextMenu>
<telerik:RadMenuItem Header="Remove" Command="{Binding RemoveCommand}" CommandParameter="{Binding ElementName=treeView, Path=SelectedItem, Mode=OneWay}" />
</ContextMenu>
</TreeView.ContextMenu>
</TreeView>
I receive an exception in Output window, like
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=treeView'. BindingExpression:Path=SelectedItem; DataItem=null; target element is 'RadMenuItem' (Name=''); target property is 'CommandParameter' (type 'Object')
I am actually using RadTreeView, but the same applies for TreeView. Why I cannot bind to TreeView’s SelectedItem property? I have tried with RelativeSource AncestorType, the same problem.
The problem is that, like the Popup control, it’s a different visual tree. The error is telling you that it is trying to find a property called ‘
CommandParameter‘ on a ‘RadMenuItem‘, because this is the DataContext it has within the ContextMenu’s visual tree.This will help you: Placement Target
I ended up setting the
CommandTargetproperty of the MenuItem to the ContextMenu’sPlacementTargetproperty, but it doesn’t look like that’s the approach you’re taking. Even still, thePlacementTargetis what you’re looking for.