我就想获取某行某列的文本,本来在winform中很简单的,却发现在wpf中还挺不好做,也许是我还没找到简单的实现。
/// /// 获取单元格文字 /// /// /// /// public static string GetCellIndex(DataGrid dataGrid1, int rowIndex, int columnIndex) { if (dataGrid1 == null) { return null; } DataGridRow rowContainer = (DataGridRow)dataGrid1.ItemContainerGenerator.ContainerFromIndex(rowIndex); DataGridCellsPresenter presenter = GetVisualChild(rowContainer); if (presenter == null) { return null; } DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex); if (cell == null) { dataGrid1.ScrollIntoView(rowContainer, dataGrid1.Columns[columnIndex]); cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex); } string text = cell.ToString(); if (Regex.IsMatch(text, ".+?:(.+)")) { text = Regex.Match(text, ".+?:(.+)").Groups[1].Value; return text; } return null; } private static T GetVisualChild(Visual parent) where T : Visual { if (parent == null) { return null; } 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); } else { break; } } return child; }