首先可以使用 DevExpress GridControl 自带的进度条控件。
但是我要用一个方法来设置所有的单元格进度,而不是每个单元格都要设置一遍,同时我想要根据进度值不同,进度条显示不同的颜色。
那么就要自己手动的编写代码来完成了。
1 、绘制一个单元格进度条形状,当进度小于50%时显示为红色。
public void DrawProgressBar(DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e) { string s = e.CellValue as string; s = s.Substring(0, e.CellValue.ToString().Length - 1); decimal percent = Convert.ToDecimal(s); int width = (int)(100 * Math.Abs(percent /100 ) * e.Bounds.Width / 100); Rectangle rect = new Rectangle(e.Bounds.X, e.Bounds.Y, width, e.Bounds.Height); Brush b = Brushes.Green; if (percent < 50) { b = Brushes.Red; } e.Graphics.FillRectangle(b, rect); }
2、点击 GridView 展开触发事件
private void gridView1_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e) { if (e.Column.FieldName == "CLASSPACE") { DrawProgressBar(e); e.Handled = true; DrawEditor(e); } }
3、上面两段代码其实效果已经出来了,只不过有一些瑕疵,单元格只显示数值,而不显示进度条(当点击单元格时数值会消失),那么需要我们再来手动的编写一段代码用来处理当单元格触发时一些操作。
private void DrawEditor(DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e) { GridCellInfo cell = e.Cell as GridCellInfo; Point offset = cell.CellValueRect.Location; BaseEditPainter pb = cell.ViewInfo.Painter as BaseEditPainter; AppearanceObject style = cell.ViewInfo.PaintAppearance; if (!offset.IsEmpty) cell.ViewInfo.Offset(offset.X, offset.Y); try { pb.Draw(new ControlGraphicsInfoArgs(cell.ViewInfo, e.Cache, cell.Bounds)); } finally { if(!offset.IsEmpty) { cell.ViewInfo.Offset(-offset.X, -offset.Y); } } }
同时将单元格设置为不可编辑状态。
附最后显示效果 :