.net 如何在XAML中设置CommandParameter?

.net 如何在XAML中设置CommandParameter?,.net,wpf,xaml,.net-4.0,.net,Wpf,Xaml,.net 4.0,我有以下XAML: <dxg:GridControl Name="theGrid" DataSource="{Binding Path=Groupings}"> <dxg:GridControl.ContextMenu> <ContextMenu> <MenuItem x:Name="gridprint" Command="{Binding Path=GridPrintCommand

我有以下XAML:

   <dxg:GridControl Name="theGrid" DataSource="{Binding Path=Groupings}">
       <dxg:GridControl.ContextMenu>
           <ContextMenu>
               <MenuItem x:Name="gridprint" Command="{Binding Path=GridPrintCommand}"/>
           </ContextMenu>
       </dxg:GridControl.ContextMenu>
   </dxg:GridControl>

这个很好用。但是我试图在XAML中设置相同的东西(CommandParameter),但我就是不能正确地设置它!我放入的所有内容都会导致BindingExpressionError或null参数。我错过了什么?

我相信应该是这个

<dxg:GridControl Name="theGrid" DataSource="{Binding Path=Groupings}">
  <dxg:GridControl.ContextMenu>
    <ContextMenu>
      <MenuItem x:Name="gridprint"
        Command="{Binding Path=GridPrintCommand}"
        CommandParameter="{Binding ElementName=theGrid}"
      />
    </ContextMenu>
  </dxg:GridControl.ContextMenu>

尝试使用以下方法:

<MenuItem x:Name="gridprint"
    CommandParameter="{Binding PlacementTarget, RelativeSource=
         {RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}" />


ContextMenus不是WPF正常VisualTree的一部分,因此您必须使用PlacementTarget进行绑定,以获取ContextMenus附加到的对象

如果我尝试此操作,我会收到以下错误消息:
System.Windows.Data错误:4:无法找到引用“ElementName=theGrid”的绑定源。BindingExpression:(无路径);DataItem=null;目标元素是“MenuItem”(Name='gridprint');目标属性为“CommandParameter”(类型为“Object”)
如果没有弄错,则与ContextMeny和GridControl之间的名称空间有关。谢谢,经过三天的搜索,我发现ContextMenus不是WPF正常VisualTree的一部分,因此,您必须使用PlacementTarget进行绑定,以获取ContextMenu所附加到的对象
<MenuItem x:Name="gridprint"
    CommandParameter="{Binding PlacementTarget, RelativeSource=
         {RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}" />