0

I have the following problem. I have a DataGrid with a ContextMenu. But when the Command is triggered the SelectedItem is always null.
Any recommendations?

Thats my 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}"

F.Wen
  • 31
  • 1
  • 6

3 Answers3

3

Thanks for your help. I fixed it this way:
CommandParameter="{Binding PlacementTarget.SelectedItem, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}"

F.Wen
  • 31
  • 1
  • 6
2

I think your answer is here: CommandParameters in ContextMenu in WPF

Another better option imho is to keep "SelectedItem" binded in your ViewModel.

Then you don't need a command parameter anymore, and you can juste use the SelectedItem binded from your ViewModel.

Community
  • 1
  • 1
Ouarzy
  • 3,015
  • 1
  • 16
  • 19
0

The problem is that the ContextMenu is in a different VisualTree.

You could use the Tag for binding the Command. See the following link

wake-0
  • 3,918
  • 5
  • 28
  • 45