我尝试做这样的事情:

<DataGrid Name="myGrid" ItemSource="{Binding Path=MyCollection}">
   <DataGrid.ContextMenu>
       <ContextMenu>
          <MenuItem
              Command="{Binding RemoveRow}"
              CommandParameter="{Binding ElementName=myGrid, Path=SelectedItem}">
       </ContextMenu>
   </DataGridContextMenu>
</DataGrid>

但我总是为空(我也尝试了SelectedIndex和SelectedValue)

如果我将以下参数传递给执行代码,它将起作用:
<MenuItem Command="{Binding RemoveRow}" CommandParameter="1">

最佳答案

在您的CommandParameter中尝试这样的操作,

<DataGrid.ContextMenu>
     <ContextMenu>
           <MenuItem Header="MyHeader"
                     Command="{Binding MyCommand}"
                     CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}, Path=PlacementTarget.SelectedItem}" />
</DataGrid.ContextMenu>

我已经测试过了,应该可以了。

关于wpf - 从xaml传递命令参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8154202/

10-12 00:28
查看更多