c# - 如何获取 DataGridRow 单元格的值?

标签 c# wpf

我目前已将此方法设置为检测对 DataGrid 中每一行的双击:

private void Row_DoubleClick(object sender, RoutedEventArgs e)
    {
        DataGridRow row = (DataGridRow)sender;
        DataRow dr = (DataRow)row.DataContext;
        string value = dr[0].ToString();
        MessageBox.Show(value);
    }

但我的问题是我似乎无法获取单元格值。如您所见,我试图获取行中第一个单元格的值,但它只会崩溃。我有什么想法可以做到这一点? :)

最佳答案

试试这个。

public static DataGridCell GetCell(DataGrid dataGrid, int row, int column)
{
    DataGridRow rowContainer = GetRow(dataGrid, row);
    if (rowContainer != null)
    {
        DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);

        // try to get the cell but it may possibly be virtualized
        DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
        if (cell == null)
        {
            // now try to bring into view and retreive the cell
            dataGrid.ScrollIntoView(rowContainer, dataGrid.Columns[column]);

            cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
        }

        return cell;
    }

    return null;
 }

关于c# - 如何获取 DataGridRow 单元格的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28533905/

相关文章:

c# - 带有 P-256 的 ECDH 使用静态 key 生成共享 key bouncy caSTLe c#

c# - 使用自定义字体的 RDLC 报告 - 调用 COM 组件已返回错误 HRESULT E_FAIL

.net - 在数据库中保存格式化文本的有意义的格式是什么?

C# MVVM 如何从模型更新 View 模型字符串

wpf - 如何重复使用相同的控件两次但保持它们之间的状态

wpf - 键入 XAML 时如何将插入符号移到结束引号之后?

c# - 为什么我的异常没有被捕获?

c# - 如何使用 lambda 指定构造函数参数?

c# - 在Linux的同一台计算机上运行多个实例时的.Net Core垃圾回收

wpf - Viewmodel 的多个实例