这是我使用WPF / C#所做的事情:
过去几天,我一直在研究和尝试其他类似的SO问题,但是没有运气。有人可以帮我解决这个问题吗?
我使用Visual Studio 2019,这是WPF Framework项目。我尝试了dsfgsho的方法。见链接Getting WPF Data Grid Context Menu Click Row
// Originally from dsfgsho, with slight changes.
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
//Get the clicked MenuItem
var menuItem = (MenuItem)sender;
//Get the ContextMenu to which the menuItem belongs
var contextMenu = (ContextMenu)menuItem.Parent;
//Find the placementTarget
var item = (DataGrid)contextMenu.PlacementTarget;
//Get the underlying item, that you cast to your object that is bound
//to the DataGrid (and has subject and state as property)
var selected_tbl_name = (DataColumn)item.SelectedCells[0].Item;
//****The last step is where I get confused and it also throws an exception.
}
XAML:
<Grid>
<DataGrid
x:Name="dataGrid_test"
ItemsSource="{Binding}"
SelectedItem="{Binding SelectedItemPorperty}"
HorizontalAlignment="Left"
Height="369"
Margin="395,10,0,0"
VerticalAlignment="Top"
Width="381"
SelectionChanged="DataGrid_SelectionChanged"
>
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Header="Select" Click="MenuItem_Click">
</MenuItem>
</ContextMenu>
</DataGrid.ContextMenu>
</DataGrid>
</Grid>
关于功能MenuItem_Click(对象发送方,RoutedEventArgs e)的最后一行:由于我将DataGrid与DataTable一起使用,因此我认为基础项将是DataTable单元格。 DataTable单元格有类型吗?我找不到它,所以我使用了DataCloumn。但是抛出了一个异常,它说“指定的参数超出有效值范围。参数名称:索引”。