简体   繁体   English

右键单击事件中的DataGrid行选择未选择行

[英]DataGrid Row Selection on Right Click Event Not Selecting Row

I have a DataGrid with a ContextMenu . 我有一个带有ContextMenuDataGrid 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 . 所以我尝试了MouseRightButtonUp事件处理程序,但最终得到了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. 然后,我尝试了SelectionChanged事件,该事件最终起作用了,但是如果连续多次SelectionChanged它,则它不会连续运行多次。 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? 目前我有哪些可用选项?

You could try setting the MouseRightClick event handler on the DataGridRow directly, like so : 您可以尝试直接在DataGridRow上设置MouseRightClick事件处理程序,如下所示:

<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! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM