How to set binding in WPF Toolkit Datagrid ContextMenu CommandParameter

I need to create a ContextMenu where I want to pass the currently selected datagrid index to the ViewModel using CommandParameter. The following Xaml code does not work. What could be the problem?

<dg:DataGrid ItemsSource="{Binding MarketsRows}" <dg:DataGrid.ContextMenu > <ContextMenu > <MenuItem Header="Add Divider" CommandParameter="{Binding Path=SelectedIndex, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type dg:DataGrid}}}" Command="{Binding Path= AddDividerCommand}"/> </ContextMenu> </dg:DataGrid.ContextMenu> </dg:DataGrid> 
+4
source share
2 answers

The context menu is not part of the same visual tree. Ancestor bindings do not work, because the context menu is not a child of the element on which it is included; in your case a datagrid.

There are some workarounds, Ive answered this question earlier here and here (view)

But what you are looking for is a placement target to do something like this (as long as AddDividerCommand is a property in a datagrid (i.e. placement target)

 <ContextMenu DataContext="{Binding RelativeSource={RelativeSource Mode=Self}, Path=PlacementTarget}"> <MenuItem Header="Add Divider" CommandParameter="{Binding Path=SelectedIndex}" Command="{Binding Path=AddDividerCommand}"/> </ContextMenu> 
+12
source

Try something like this in your CommandParameter,

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

I have already tested it and it should work.

+2
source

Source: https://habr.com/ru/post/1309929/


All Articles