private void Dg_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e) { Console.WriteLine("start"); foreach (DataGridCellInfo info in dg.SelectedCells) { FrameworkElement element = info.Column.GetCellContent(info.Item); string str = ((TextBlock)info.Column.GetCellContent(info.Item)).Text; Console.WriteLine(str); } }
private void Button_Click(object sender, RoutedEventArgs e) { DataGridCellInfo info = new DataGridCellInfo(dg.Items[0], dg.Columns[2]); Console.WriteLine("start"); FrameworkElement element = info.Column.GetCellContent(info.Item); string str = ((TextBlock)info.Column.GetCellContent(info.Item)).Text; Console.WriteLine(str); }
private void Button_Click(object sender, RoutedEventArgs e) { DataGridCell cell = dg.GetCell(1, 2); TextBlock tb = cell.Content as TextBlock; Console.WriteLine(tb.Text); } public static class DataGridExtension { /// <summary> /// 获取DataGrid控件单元格 /// </summary> /// <param name="dataGrid">DataGrid控件</param> /// <param name="rowIndex">The line number of the cell to </ param> /// <param name = "columnIndex"> column number of the cell to </ param> /// <Returns> specified cell </ Returns> public static DataGridCell GetCell ( the this the dataGrid dataGrid, int rowIndex, int columnIndex) { the DataGridRow rowContainer = dataGrid.GetRow (rowIndex); IF ! (rowContainer = null ) { DataGridCellsPresenter Presenter = GetVisualChild <DataGridCellsPresenter> (rowContainer); DataGridCell Cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex); if (cell == null) { dataGrid.ScrollIntoView(rowContainer, dataGrid.Columns[columnIndex]); cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex); } return cell; } return null; } /// <summary> /// 获取DataGrid的行 /// </summary> /// <param name="dataGrid">DataGrid控件</param> /// <param name="rowIndex">DataGrid行号</param> /// <returns>指定的行号</returns> public static DataGridRow GetRow(this DataGrid dataGrid, int rowIndex) { DataGridRow rowContainer = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex); if (rowContainer == null) { dataGrid.UpdateLayout(); dataGrid.ScrollIntoView(dataGrid.Items[rowIndex]); rowContainer =(The DataGridRow) dataGrid.ItemContainerGenerator.ContainerFromIndex (rowIndex); } return rowContainer; } /// <Summary> /// Get parent visual objects of a specified type of visual object sub /// </ Summary> / // <typeParam name = "T"> visual Object type </ typeParam> /// <param name = "parent"> parent visual object </ param> /// <Returns> designated first sub-type visual object </ Returns> public static T GetVisualChild <T> (the visual parent) WHERE T: the 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; } }