我需要创建一个ContextMenu,我想使用CommandParameter将当前选择的datagrid索引传递给ViewModel。以下Xaml代码不起作用。可能是什么问题?
<dg:DataGrid ItemsSource="{Binding MarketsRows}"
<dg:DataGrid.ContextMenu >
<ContextMenu >
<MenuItem Header="Add Divider"
CommandParameter="{Binding Path=SelectedIndex,
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type dg:DataGrid}}}"
Command="{Binding Path= AddDividerCommand}"/>
</ContextMenu>
</dg:DataGrid.ContextMenu>
</dg:DataGrid>
答案 0 :(得分:12)
上下文菜单不是同一视觉树的一部分。祖先绑定不起作用,因为上下文菜单不是它所在元素的子元素;在你的情况下是datagrid。
有一些解决方法,我以前回答过这个问题here和here (kind of)
但你要找的是放置目标来做这样的事情(只要AddDividerCommand是数据网格上的属性(即放置目标)
<ContextMenu DataContext="{Binding RelativeSource={RelativeSource Mode=Self}, Path=PlacementTarget}">
<MenuItem
Header="Add Divider"
CommandParameter="{Binding Path=SelectedIndex}"
Command="{Binding Path=AddDividerCommand}"/>
</ContextMenu>
答案 1 :(得分:3)
在CommandParameter中尝试这样的事情,
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Header="MyHeader"
Command="{Binding MyCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}, Path=PlacementTarget.SelectedItem}" />
</DataGrid.ContextMenu>
我已经测试了它,它应该可以工作。