如何使用ContextMenu访问DataGrid的单元格值?

时间:2019-05-24 18:14:46

标签: c# wpf datagrid

这是我使用WPF / C#所做的事情:

  1. 使用DataGrid显示数据表中的数据。此步骤工作正常。
  2. 将ContextMenu添加到DataGrid。由于上下文菜单正确显示,这似乎也很好。
  3. 使用上下文菜单访问在DataGrid中选择的单元格,并将该单元格的值用于进一步的工作。这是我坚持的步骤。

过去几天,我一直在研究和尝试其他类似的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。但是抛出了一个异常,它说“指定的参数超出有效值范围。参数名称:索引”。

0 个答案:

没有答案
相关问题