简体   繁体   English

WPF Datagrid ContextMenu SelectedItem

[英]WPF Datagrid ContextMenu SelectedItem

I have the following problem. 我有以下问题。 I have a DataGrid with a ContextMenu. 我有一个带有ContextMenu的DataGrid。 But when the Command is triggered the SelectedItem is always null. 但是,当命令被触发时,SelectedItem始终为null。
Any recommendations? 有什么建议吗?

Thats my ContextMenu: 那就是我的ContextMenu:

<DataGrid.ContextMenu>
  <ContextMenu>
  <MenuItem Command="{Binding OpenFileCommand}"
           CommandParameter="{Binding Path=SelectedItem,
           RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"
           Header="open file" />

i also tried: CommandParameter="{Binding ElementName=nameOfGrid, Path=SelectedItem}" 我也尝试过: CommandParameter="{Binding ElementName=nameOfGrid, Path=SelectedItem}"

I think your answer is here: CommandParameters in ContextMenu in WPF 我认为您的答案在这里: WPF中ContextMenu中的CommandParameters

Another better option imho is to keep "SelectedItem" binded in your ViewModel. 恕我直言,另一个更好的选择是在ViewModel中绑定“ SelectedItem”。

Then you don't need a command parameter anymore, and you can juste use the SelectedItem binded from your ViewModel. 然后,您不再需要命令参数,您就可以使用从ViewModel绑定的SelectedItem。

Thanks for your help. 谢谢你的帮助。 I fixed it this way: 我以这种方式修复了它:
CommandParameter="{Binding PlacementTarget.SelectedItem, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}"

The problem is that the ContextMenu is in a different VisualTree . 问题在于ContextMenu位于不同的VisualTree

You could use the Tag for binding the Command . 您可以使用Tag来绑定Command See the following link 见以下链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM