Bind to parent DataContext in DataTemplate

I am trying to associate the MenuItem command with the command contained in UserControl.DataContext . I found a couple of similar questions, but the solution they say doesn't suit me:

 <UserControl ...> <UserControl.Resources> <DataTemplate x:Key="TileItemStye"> <Grid Width="100" Height="100"> <Grid.ContextMenu> <ContextMenu> <MenuItem Header="Remove" Command="{Binding DataContext.RemoveItem, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}"> </MenuItem> </ContextMenu> </Grid.ContextMenu> </Grid> </DataTemplate> </UserControl.Resources> <Grid> <ListView ItemsSource="{Binding Path=Files}" ItemTemplate="{DynamicResource TileItemStye}" > <ListView.ItemsPanel> <ItemsPanelTemplate> <WrapPanel /> </ItemsPanelTemplate> </ListView.ItemsPanel> </ListView> </Grid> 

UserControl DataContext is a ViewModel with ICommand RemoveItem and ObservableCollection<FileViewModel> Files.

+7
source share
2 answers

If you are on .NET 4 a really more elegant solution:

 <UserControl Name="uc" ...> <!-- ... --> <MenuItem Header="Remove" Command="{Binding DataContext.RemoveItem, Source={x:Reference uc}}"/> 

(this requires the template to remain in resources, otherwise there will be a cyclic dependency error)

+13
source

Menus are not drawn in the same visual data tree as your controls, so RelativeSource bindings do not work

You need to bind to your ContextMenu 's PlacementTarget to access the main visual tree

 <MenuItem Header="Remove" Command="{Binding PlacementTarget.DataContext.RemoveItem, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}" /> 
+4
source

All Articles