绑定到 DataTemplate 中的父 DataContext
我正在尝试将 MenuItem 的命令绑定到 UserControl.DataContext 中包含的命令。我发现了几个类似的问题,但根据他们的解决方案对我来说失败了:
<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 是带有 ICommand
RemoveItem 和 ObservableCollection
文件的 ViewModel。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用.NET 4,确实有一个更优雅的解决方案:
(这要求模板保留在资源中,否则会出现循环依赖错误)
If you are on .NET 4 there indeed is a more elegant solution:
(This requires that the template stays in the Resources, otherwise there will be a cyclical dependency error)
菜单与控件不在同一视觉树中绘制,这就是为什么relativesource绑定不起作用的原因
您需要绑定到
ContextMenu
的PlacementTarget
才能访问主菜单视觉树Menus are not drawn in the same Visual Tree as your Controls, which is why the RelativeSource binding does not work
You need to bind to the
PlacementTarget
of yourContextMenu
to access the main Visual Tree