WPF DataGrid 获得某行某列单元格

/// <summary>
/// 行、列从0开始计数
/// </summary>
/// <param name="rowIndex"></param>
/// <param name="columnIndex"></param>
/// <param name="dg"></param>
/// <returns></returns>
public DataGridCell GetCell(DataGrid dg,int rowIndex, int columnIndex)
{
    DataGridRow row = dg.ItemContainerGenerator.ContainerFromIndex(rowIndex) as DataGridRow;
    DataGridCellsPresenter p = GetVisualChild<DataGridCellsPresenter>(row);
    DataGridCell cell = p.ItemContainerGenerator.ContainerFromIndex(columnIndex) as DataGridCell;
    return cell;
}

static T GetVisualChild<T>(Visual parent) where T : Visual
{
    T child = default(T);
    int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
    for (int i = 0; i < numVisuals; i++)
    {
        Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
        child = v as T;
        if (child == null)
        {
            child = GetVisualChild<T>(v);
        }
        if (child != null)
        {
            break;
        }
    }
    return child;
}

使用

DataGridCell cell = GetCell(yourDataGrid,1, 1);
cell.Background = new SolidColorBrush(Colors.Red);

参考资料

How to Change Cell background color in WPF Datagrid

posted @ 2020-06-16 21:30  Lulus  阅读(1774)  评论(0编辑  收藏  举报