同样的问题:带有 ItemsSource 的 WPF ContextMenu - 如何在每个项目中绑定到 Command?
我尝试如下实现它,但没有骰子。
目前在我的 XAML 中有:
<DataGrid.ContextMenu>
<ContextMenu ItemsSource="{Binding Users}">
<ContextMenu.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=UID, Converter={StaticResource UserConverter}}"/>
</DataTemplate>
</ContextMenu.ItemTemplate>
<ContextMenu.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="Command" Value="{Binding ReassignFileCommand}" />
</Style>
</ContextMenu.ItemContainerStyle>
</ContextMenu>
</DataGrid.ContextMenu>
如果我使用,命令确实有效:
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Header="Woooo" Command="{Binding ReassignFileCommand}" />
</ContextMenu>
</DataGrid.ContextMenu>
需要更改为(解决方案):
<Setter Property="Command" Value="{Binding Path=DataContext.ReassignFileCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}" />