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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM