WPF DataGrid 单元格突出显示
备注: DataGrid Name="dgv1" LoadingRow="Dgv1_OnLoadingRow"
private void Dgv1_OnLoadingRow(object sender, DataGridRowEventArgs e) { e.Row.Loaded += Row_Loaded; } private void Row_Loaded(object sender, RoutedEventArgs e) { var dataGridRow = sender as DataGridRow; var dataRow = dataGridRow.Item as DataRowView; var str = dataRow["ExpiredQty"].ToString(); if (MyConvertHelper.ToInt32(str, 0) > 0) { DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(dataGridRow); if (presenter == null) { return; } var colIndex = 0; for (int index = 0; index < this.dgv1.Columns.Count; index++) { var col = this.dgv1.Columns[index]; if (col.Header.ToString().Contains("近效期")) { colIndex = index; break; } } DataGridCell cell = presenter?.ItemContainerGenerator.ContainerFromIndex(colIndex) as DataGridCell; if (cell != null) { //cell.Background = new SolidColorBrush(Colors.Red); cell.Foreground = new SolidColorBrush(Colors.Red); } } } 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); if (child != null) break; } return child; }
效果图:
参考:https://stackoverflow.com/questions/17894506/visualtreehelper-getchildrencount-return-0
浙公网安备 33010602011771号