Search code examples
c#wpfdatagridmvvm-lightrelaycommand

SelectedItem set after Right Click event on DataGrid


I have a DataGrid as below

<DataGrid Margin="10,89,10,10" 
          AlternatingRowBackground="#FFB9E2FF" 
          ItemsSource="{Binding ResultDetails, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
          SelectedItem="{Binding SelectedItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
          AutoGenerateColumns="True" 
          CanUserAddRows="False" 
          IsReadOnly="True" 
          SelectionMode="Single">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="MouseRightButtonUp">
            <cmd:EventToCommand Command="{Binding ResultGridMouseClickCommand, Mode=OneWay}" />
        </i:EventTrigger>
        <i:EventTrigger EventName="MouseDoubleClick">
            <cmd:EventToCommand Command="{Binding ResultGridDblClickCommand}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</DataGrid>

And I have a RelayCommand to handle MouseRightButtonUp event

private void ExecResultGridMouseClickCommand()
{
    if (SelectedItem == null) return;

    DisplayInfo(SelectedItem);
}

Let's say I have 5 items in DataGrid: Item1 Item2 Item3 Item4 Item5

When DataGrid init, SelectedItem is null. Then user right click on Item3, RelayCommand fire, but SelectedItem still is null. User right click on Item1, RelayCommand fire again, however, SelectedItem return Item3, and my code was display wrong item's details.

Is it possible to retrieve which item are selected in MouseRightButtonUp event? Or I should use other event instead?


Solution

  • IMHO, the best approach is to apply a style to the DataGridRow, that way you ensure that the command is being applied to the item the user is actually clicking and you forget about the SelectedItem. Note the following:

    • DataContext will now the item itself instead of the collection.
    • You cannot use <i:Interaction.Triggers> inside a Style. There seem to be workarounds to this. Or you can try switching to the mighty Attached Command Behaviors: you have an example of usage inside a style here, second answer.