private void Button_Click(objectsender, RoutedEventArgs e)
{
DataGridCell cell= dg.GetCell(1, 2);
TextBlock tb= cell.Content asTextBlock;
Console.WriteLine(tb.Text);
}public static classDataGridExtension
{///
///获取DataGrid控件单元格///
/// DataGrid控件
/// 单元格所在的行号
/// 单元格所在的列号
/// 指定的单元格
public static DataGridCell GetCell(this DataGrid dataGrid, int rowIndex, intcolumnIndex)
{
DataGridRow rowContainer=dataGrid.GetRow(rowIndex);if (rowContainer != null)
{
DataGridCellsPresenter presenter= GetVisualChild(rowContainer);
DataGridCell cell=(DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);if (cell == null)
{
dataGrid.ScrollIntoView(rowContainer, dataGrid.Columns[columnIndex]);
cell=(DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);
}returncell;
}return null;
}///
///获取DataGrid的行///
/// DataGrid控件
/// DataGrid行号
/// 指定的行号
public static DataGridRow GetRow(this DataGrid dataGrid, introwIndex)
{
DataGridRow rowContainer=(DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex);if (rowContainer == null)
{
dataGrid.UpdateLayout();
dataGrid.ScrollIntoView(dataGrid.Items[rowIndex]);
rowContainer=(DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex);
}returnrowContainer;
}///
///获取父可视对象中第一个指定类型的子可视对象///
/// 可视对象类型
/// 父可视对象
/// 第一个指定类型的子可视对象
public static T GetVisualChild(Visual parent) whereT : 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 asT;if (child == null)
{
child= GetVisualChild(v);
}if (child != null)
{break;
}
}returnchild;
}
}