/// <summary> /// 获取DataGrid控件单元格 /// </summary> /// <param name="dataGrid">DataGrid控件</param> /// <param name="rowIndex">单元格所在的行号</param> /// <param name="columnIndex">单元格所在的列号</param> /// <returns>指定的单元格</returns> public static DataGridCell GetCell(this DataGrid dataGrid, int rowIndex, int columnIndex) { var rowContainer = dataGrid.GetRow(rowIndex); if (rowContainer == null) { return(null); } var presenter = YControlHelper.GetVisualChild <DataGridCellsPresenter>(rowContainer); if (presenter == null) { return(null); } var cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex); if (cell != null) { return(cell); } dataGrid.ScrollIntoView(rowContainer, dataGrid.Columns[columnIndex]); cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex); return(cell); }
/// <summary> /// 设置指定单元格的背景色 /// </summary> public static void SetCellBackground(this DataGrid dataGrid, int rowIndex, int columnIndex, Brush brush, string toolTip = null) { try { var row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex); var presenter = YControlHelper.GetVisualChild <DataGridCellsPresenter>(row); var cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex); var baseStyle = dataGrid.FindResource("DataGridCellStyle") as Style; var celStyle = new Style(typeof(DataGridCell), baseStyle); celStyle.Setters.Add(new Setter { Property = Control.BackgroundProperty, Value = brush }); cell.Style = celStyle; cell.ToolTip = toolTip; } catch (Exception) { // } }