由于ContextMenu不继承父级的DataContext,所以如果要绑定父级的DataContext,直接DataContext=“{Binding}”是行不通的。因此可通过以下两个方式解决绑定的问题。
1、使用资源的方式
1 <Button Content="Test" Command="{Binding TestCommand}"> 2 <Button.Resources> 3 <vm:ThreeViewModel x:Key="Three"/> 4 </Button.Resources> 5 <Button.ContextMenu> 6 <ContextMenu> 7 <MenuItem Header="测试" Command="{Binding TestCommand,Source={StaticResource Three}}"/> 8 </ContextMenu> 9 </Button.ContextMenu> 10 </Button> 11
2、利用ContextMenu的PlacementTarget属性
<Button Content="Test" Command="{Binding TestCommand}"> <Button.ContextMenu> <ContextMenu> <MenuItem Header="测试" Command="{Binding PlacementTarget.DataContext.TestCommand, RelativeSource={RelativeSource AncestorType=ContextMenu} }"/> </ContextMenu> </Button.ContextMenu> </Button>