How to get value of a cell from datagrid in WPF? [duplicate]

二次信任 提交于 2019-12-21 05:45:17

问题


Possible Duplicate:
Select DataGridCell from DataGrid

I have a datagrid in WPF with some columns and rows. when I click on a row I want to get the first column of the selected row. How can I do it? can I use LINQ for that? thanx


回答1:


You can simply use this extension method-

public static DataGridRow GetSelectedRow(this DataGrid grid)
{
    return (DataGridRow)grid.ItemContainerGenerator.ContainerFromItem(grid.SelectedItem);
}

and you can get a cell of a DataGrid by an existing row and column id(0 in your case):

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

        if (presenter == null)
        {
            grid.ScrollIntoView(row, grid.Columns[column]);
            presenter = GetVisualChild<DataGridCellsPresenter>(row);
        }

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

Check this link for details - Get WPF DataGrid row and cell




回答2:


var firstSelectedCellContent = this.dataGrid.Columns[0].GetCellContent(this.dataGrid.SelectedItem);
var firstSelectedCell = firstSelectedCellContent != null ? firstSelectedCellContent.Parent as DataGridCell : null;

This way you can get FrameworkElement that is a content of a DataGridCell and a DataGridCell itself.

Note that if DataGrid has EnableColumnVirtualization = True, then you might get null values from the code above.

To get the actual value from a data source, for a specific DataGridCell, is a little more complicated. There is no general way to do this, because DataGridCell can be constituted from multiple values (properties) from the backing data source, so you are going to need to handle this for a specific DataGridColumn.



来源:https://stackoverflow.com/questions/11070873/how-to-get-value-of-a-cell-from-datagrid-in-wpf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!