datagrid获取单元格索引

是否有可能获取列标题=“column4”并且行包含“232”的单元格索引,例如我上传的屏幕截图是否可以获得红色单元格索引而不是使其变为红色? 如果wpf datagrid有那个函数wpf工具包数据网格有吗? 列和行正在从代码后面添加 在此处输入图像描述

您应该通过Style / Trigger或使用转换器Binding来执行此操作

            

默认情况下, DataGrid使用虚拟化,因此只会加载此刻对用户可见的DataGridRows 。 其他行将在可见后创建,因此如果您尝试在后面的代码中设置一些单元格可能会变得非常混乱(您尝试访问的单元格可能尚不存在。)

要在索引行/列获取DataGridCell ,您可以定义一个帮助器类( DataGridHelper )并像这样使用它

 DataGridCell cell = DataGridHelper.GetCell(dataGrid, 0, 2); if (cell != null) { cell.Background = Brushes.Red; } 

DataGridHelper

 static class DataGridHelper { static public DataGridCell GetCell(DataGrid dg, int row, int column) { DataGridRow rowContainer = GetRow(dg, row); if (rowContainer != null) { DataGridCellsPresenter presenter = GetVisualChild(rowContainer); // try to get the cell but it may possibly be virtualized DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column); if (cell == null) { // now try to bring into view and retreive the cell dg.ScrollIntoView(rowContainer, dg.Columns[column]); cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column); } return cell; } return null; } static public DataGridRow GetRow(DataGrid dg, int index) { DataGridRow row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(index); if (row == null) { // may be virtualized, bring into view and try again dg.ScrollIntoView(dg.Items[index]); row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(index); } return row; } static T GetVisualChild(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(v); } if (child != null) { break; } } return child; } }