1
votes

I have a DataGrid with a ContextMenu. What I would like is when the context menu is brought up (via a right click), I want to get column data on the selected row. This data will be used to confirm whether or not some context menu options should be enabled or not.

So I tried the MouseRightButtonUp event handler, but I ended up getting a NullReferenceException.

<DataGrid MouseRightButtonUp="DataGrid_MouseRightButtonUp">

private void DataGrid_MouseRightButtonUp(object sender, MouseButtonEventArgs e) {
MessageBox.Show(((DataRowView)DataGrid.SelectedItem).Row.ItemArray[0].ToString());
}

I then tried the SelectionChanged event which ended up working however, it would not work more than once on a row if it was selected more then once. I need it such that for every time a row is right clicked, the event will fire off and return the column data. Also this event fired off on left clicks which are not needed.

What are my available options at this point?

1
Are you using MVVM? Show your XAML so we can better direct you. - David Bentley

1 Answers

2
votes

You could try setting the MouseRightClick event handler on the DataGridRow directly, like so :

<DataGrid.Resources>
    <Style TargetType="DataGridRow">
      <EventSetter Event="MouseRightButtonUp" Handler="YourHandler"/>
    </Style>
</DataGrid.Resources>

That way, you won't have to try and find the clicked row, which limits the possibility for errors. You will directly have access to the row in the event handler.

Hope that helps!