我如何在XAML中设置CommandParameter?如何在、XAML、CommandParameter

2023-09-03 01:44:25 作者:じ 跪下叫姐

我有以下的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>

在GridPrintCommand执行,其参数为GridPrintCommand.Execute(参数)方法为空。我想设置的参数网格控件。我能做到这一点,在code-背后是这样的:

When GridPrintCommand executes, its parameter to the GridPrintCommand.Execute(param) method is null. I want to set the parameter to the grid control. I can do that in the code-behind like this:

gridprint.CommandParameter = theGrid;

这工作得很好。但我想设置在XAML同样的事情(CommandParameter),我只是无法得到它的权利!一切我在BindingEx pressionError或空参数投入的结果。我在想什么?

This works fine. But I'm trying to set the same thing (CommandParameter) in the XAML, and I just can't get it right! Everything I put results in a BindingExpressionError or a null parameter. What am I missing?

推荐答案

请尝试使用这样的:

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

ContextMenus不是WPF的正常VisualTree的一部分,所以可以选择使用PlacementTarget获取文本菜单附加到对象结合

ContextMenus are not part of the WPF's normal VisualTree, so you have to bind using the PlacementTarget to get the object the ContextMenu is attached to