Bor*_*itz 4 c# wpf xaml binding
我需要创建一个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>
Run Code Online (Sandbox Code Playgroud)
Ara*_*and 12
上下文菜单不是同一可视树的一部分.祖先绑定不起作用,因为上下文菜单不是它所在元素的子元素; 在你的情况下数据网格.
但是你要找的是放置目标来做这样的事情(只要AddDividerCommand是datagrid上的属性(即放置目标)
<ContextMenu DataContext="{Binding RelativeSource={RelativeSource Mode=Self}, Path=PlacementTarget}">
<MenuItem
Header="Add Divider"
CommandParameter="{Binding Path=SelectedIndex}"
Command="{Binding Path=AddDividerCommand}"/>
</ContextMenu>
Run Code Online (Sandbox Code Playgroud)
小智 6
在您的 CommandParameter 中尝试类似的操作,
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Header="MyHeader"
Command="{Binding MyCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}, Path=PlacementTarget.SelectedItem}" />
</DataGrid.ContextMenu>
Run Code Online (Sandbox Code Playgroud)
我已经测试过了,它应该可以工作。