Change DataGrid cell value programmatically in WPF

前端 未结 2 1678
渐次进展
渐次进展 2020-12-15 01:59

I have a DataGrid view that fill it\'s content by a list in run time. I want to change (For example) cell value in row:2 and column:3.

How can I do this

2条回答
  •  执笔经年
    2020-12-15 02:25

    For example if you have TextBox on your grid

    
    

    Full sample

    
          
            
            
            
          
    
          
            
            
            
          
    
          ...
          
          ...
        
    

    You can use these helpers; you have this link http://techiethings.blogspot.fr/2010/05/get-wpf-datagrid-row-and-cell.html.

    Iadded the code in order to save code on stackoverflow, in the case where the site become closed

    public static DataGridRow GetRow(this DataGrid grid, int index)
    {
        DataGridRow row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index);
        if (row == null)
        {
            // May be virtualized, bring into view and try again.
            grid.UpdateLayout();
            grid.ScrollIntoView(grid.Items[index]);
            row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index);
        }
        return row;
    }
    
    public static DataGridCell GetCell(this DataGrid grid, DataGridRow row, int column)
    {
        if (row != null)
        {
            DataGridCellsPresenter presenter = GetVisualChild(row);
    
            if (presenter == null)
            {
                grid.ScrollIntoView(row, grid.Columns[column]);
                presenter = GetVisualChild(row);
            }
    
            DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
            return cell;
        }
        return null;
    }
    
    public static DataGridCell GetCell(this DataGrid grid, int row, int column)
    {
        DataGridRow rowContainer = grid.GetRow(row);
        return grid.GetCell(rowContainer, column);
    }
    

提交回复
热议问题