I have a datagrid being binded to an ObservableCollection. The data grid has a context menu. When context menu item is clicked, the binded command gets triggered, but I would like to pass command parameter that is binded to the Id of the data grid row that is selected. The command gets triggered but the parameter is null.
Below is the code that I have tried.
<DataGrid Name="users" ItemsSource="{Binding UsersModel}" CanUserAddRows="False" IsReadOnly="True" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Id}" Header="User Id" Width="auto"/>
<DataGridTextColumn Binding="{Binding Name}" Width="*" Header="User Name"/>
<DataGridTextColumn Binding="{Binding IsRegistered, Converter={StaticResource BoolToYesNoConverter}}" Width="auto" Header="Registered" />
<DataGridTextColumn Binding="{Binding RegisteredOn}" Width="*" Header="Registration Date"/>
</DataGrid.Columns>
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Header="Modify" Command="{Binding Modify}" CommandParameter="{Binding Id}"/>
<MenuItem Header="Delete" Command="{Binding Delete}" CommandParameter="{Binding Id}" />
</ContextMenu>
</DataGrid.ContextMenu>
</DataGrid>
I am expecting the Id of the selected row be passed as the command parameter.
I would create a SelectedRow property on your viewmodel to store the selected row in the grid, then bind the context menu item command to a command on the viewmodel that references the SelectedRow property. I had to use the PlacementTarget on the context menu relative source.
// in viewmodel
public DelegateCommand ModifyCommand { get; }
ModifyCommand = new DelegateCommand(() => { var Id = SelectedRow.Id; //... });
private UsersModel _selectedRow;
public UsersModel SelectedRow
{
get => _selectedRow;
set
{
_selectedRow = value;
OnPropertyChanged(nameof(SelectedRow));
}
}
// in view
DataGrid Name="users" ItemsSource="{Binding Items}" CanUserAddRows="False" IsReadOnly="True" AutoGenerateColumns="False"
SelectedItem="{Binding SelectedRow, Mode=TwoWay}" >
// and on context menu
<MenuItem Header="Modify" Command="{Binding PlacementTarget.DataContext.ModifyCommand,
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}" />