![](/img/trans.png)
[英]WPF Contextmenu itemtemplate commandParameter binding returns null
[英]How to set a binding in WPF Toolkit Datagrid's ContextMenu CommandParameter
我需要创建一个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>
上下文菜单不是同一可视树的一部分。 祖先绑定不起作用,因为上下文菜单不是它所在元素的子元素; 在你的情况下数据网格。
但是你要找的是放置目标来做这样的事情(只要AddDividerCommand是datagrid上的属性(即放置目标)
<ContextMenu DataContext="{Binding RelativeSource={RelativeSource Mode=Self}, Path=PlacementTarget}">
<MenuItem
Header="Add Divider"
CommandParameter="{Binding Path=SelectedIndex}"
Command="{Binding Path=AddDividerCommand}"/>
</ContextMenu>
在CommandParameter中尝试这样的事情,
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Header="MyHeader"
Command="{Binding MyCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}, Path=PlacementTarget.SelectedItem}" />
</DataGrid.ContextMenu>
我已经测试了它,它应该工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.