Bind to parent DataContext within DataTemplate

bkovacic picture bkovacic · Sep 29, 2011 · Viewed 7.8k times · Source

I'm trying to bind MenuItem's Command to command contained in UserControl.DataContext. I've found couple of similar question, but solution according to them is failing to 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's DataContext is ViewModel with ICommand RemoveItem and ObservableCollection<FileViewModel> Files.

Answer

H.B. picture H.B. · Sep 30, 2011

If you are on .NET 4 there indeed is a more elegant solution:

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

(This requires that the template stays in the Resources, otherwise there will be a cyclical dependency error)