绑定到DataTemplate中的父DataContext [英] Bind to parent DataContext within DataTemplate
本文介绍了绑定到DataTemplate中的父DataContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图将MenuItem的Command绑定到包含在 UserControl.DataContext
中的命令。我找到了几个类似的问题,但根据他们的解决方案是没有给我的:
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的DataContext是ViewModel, code> ICommand RemoveItem和 ObservableCollection< FileViewModel>
文件。
UserControl's DataContext is ViewModel with ICommand
RemoveItem and ObservableCollection<FileViewModel>
Files.
推荐答案
如果你在.NET 4上确实有一个更优雅的解决方案:
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}}"/>
(这要求模板保留在Resources中,否则会有循环依赖错误)
这篇关于绑定到DataTemplate中的父DataContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文