DataGrid 属于一种 ItemsControl, 因此,它有 Items 属性并且用ItemContainer 封装它的 items. 但是,WPF中的DataGrid 不同于Windows Forms中的 DataGridView。 在DataGrid的Items集合中,DataGridRow是一个Item,但是,它里面的单元格却是被封装在 DataGridCellsPresenter 的容器中;因此,我们不能使用像DataGridView.Rows.Cells 这样的语句去获得单元格的内容。但是,在WPF中我们可以通过可视树(VisualTree)去进入到控件“内部“, 那么,我们当然可以通过VisualTree进入DataGrid中的 DataGridRow 和 DataGridCellsPresenter,并且得到在DataGridCellsPresenter中的实例, 大家可以通过以下的代码遍历VisualTree。
DataGridRow rowContainer = (DataGridRow)dataGrid1.ItemContainerGenerator.ContainerFromIndex(rowIndex);
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);
DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);
// ...
public 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);
else
break;
}
return child;
}