DataGrid how to get CurrentCell value

I need to access the value that underlies the active DataGrid cell (a cell with a black border around it).

Fortunately, the DataGrid has many properties, such as CurrentCell, CurrentItem SelectedCells SelectedItem, and SelectedItems, which seem to provide me with the data I need.

However, I did not understand how easy it is to access the cell. I also changed ...

SelectionMode="Single" SelectionUnit="Cell"

... but in the end I had to do something like this:

DataGridCellInfo cellInfo = dataGrid.CurrentCell;

if(null != cellInfo && cellInfo.IsValid)
{
    object[] array = cellInfo.Item as object[];
    if (null != array && cellInfo.Column.DisplayIndex >= 0 && cellInfo.Column.DisplayIndex < array.Length) 
    {
        object cellValue = array[cellInfo.Column.DisplayIndex];
        if (null != cellValue) 
        {
            // Here we are
        }
    }
}

, . , cellInfo.Column( ), . , - , , , DataGrid, , .

.

UPDATE

Quartermeister , , . , DisplayIndex, , .

+3
1

. , DataGridColumn . A DataGridTemplateColumn, , DataTemplate. , .

, DataGridBoundColumn (, DataGridTextColumn). , , . , - ( , , ElementName RelativeSource, , , DataGridBoundColumn):

var cellInfo = dataGrid.CurrentCell;
if (cellInfo != null)
{
    var column = cellInfo.Column as DataGridBoundColumn;
    if (column != null)
    {
        var element = new FrameworkElement() { DataContext = cellInfo.Item };
        BindingOperations.SetBinding(element, FrameworkElement.TagProperty, column.Binding);
        var cellValue = element.Tag;
    }
}

, , , DisplayIndex, , , .

+6

Source: https://habr.com/ru/post/1755127/


All Articles