You can reference the DataContext
fine even from a ContextMenu
. Just got to use PlacementTarget
to route your Binding
's.
Not sure where you have this View
command declared so I'll describe both methods.
1: View
command belongs to the ItemSource
type T
of the ListBox
(In other words, it's in the class that forms the child elements of the ListBox
)
Pretty simple we set the DataContext
of the ContextMenu
same as it's PlacementTarget
which is the Grid
.
...
<Grid.ContextMenu>
<ContextMenu DataContext="{Binding RelativeSource={RelativeSource Self}, Path=PlacementTarget.DataContext}">
<MenuItem Command="{Binding Path=View}">
<MenuItem.Header>
...
2: If View
command is in the VM CategoryDetails
as a sibling of Items
property.
With this approach, We set the DataContext
of the ListBox
which is the CategoryDetails
VM as the Tag
of the Grid
element which ContextMenu
attaches to. Now inside the ContextMenu
we bind the MenuItem.Command
to the ContextMenu
's PlacementTarget.Tag.View
...
<Grid Margin="5 10 10 5"
Tag="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type ListBox}},
Path=DataContext}">
<Grid.ContextMenu>
<ContextMenu>
<MenuItem Command="{Binding Path=PlacementTarget.Tag.View, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}">
...
You can substitute Tag
with an Attached Property if you do not want to use Tag
for this.