Reputation: 6518
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.
Upvotes: 0
Views: 2222
Reputation: 488
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 CommandTarget
property of the MenuItem to the ContextMenu's PlacementTarget
property, but it doesn't look like that's the approach you're taking. Even still, the PlacementTarget
is what you're looking for.
Upvotes: 2