F.Wen
F.Wen

Reputation: 61

WPF Datagrid ContextMenu SelectedItem

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

Upvotes: 1

Views: 4091

Answers (3)

F.Wen
F.Wen

Reputation: 61

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

Upvotes: 5

wake-0
wake-0

Reputation: 3968

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

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

Upvotes: 0

Ouarzy
Ouarzy

Reputation: 3043

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.

Upvotes: 2

Related Questions