DevExpress提供进度条的控件ProgressBarControl,并且能在GridView的单元格中使用,效果图如图所示
关于单元格绑定progressBarControl,这里我简单介绍一下,列的ColumnEdit属性选择ProgressBarControl,然后设置选择的repositoryitemprogressBar1的ShowTitle属性来显示中间的百分数文本即可(其中,这里的数据源要求为整数型,如果你的字段值为小数类型的话,比如0.5,绑定字段的时候乘以100,改成50,这里的%是控件本身会显示的,不需要设置displayformat)。
ProgressBarControl使用起来简单快捷,但是如果想控制当小于某个值的时候用颜色预警,ProgressbarControl暂时还没有提供这个功能,所以只能自己利用GridView的CustomDrawCell的单元格绘制事件来实现此需求。
代码直接copy调用即可使用:
/// <summary>
/// 自定义进度条列
/// </summary>
/// <param name="view"></param>
/// <param name="fieldName">列的字段名</param>
/// <param name="warningValue"></param>
/// <param name="lessColor"></param>
/// <param name="greaterColor"></param>
public static void CustomProgressBarColumn(DevExpress.XtraGrid.Views.Grid.GridView view, string fieldName, int warningValue=50, Brush lessColor = null, Brush greaterColor = null)
{
var col = view.Columns[fieldName];
if (col == null) return;
col.AppearanceCell.Options.UseTextOptions = true;
col.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
view.CustomDrawCell += (s, e) =>
{
if (e.Column.FieldName == fieldName)
{
DrawProgressBar(e,warningValue,lessColor,greaterColor);
e.Handled = true;
DrawEditor(e);
}
};
}
static void DrawProgressBar(DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e, int warningValue = 50, Brush lessColor = null, Brush greaterColor = null)
{
decimal percent = e.CellValue == null ? 0m : (decimal)e.CellValue;
int width = (int)(percent * e.Bounds.Width);
Rectangle rect = new Rectangle(e.Bounds.X, e.Bounds.Y, width, e.Bounds.Height);
Brush b = Brushes.Green;
if (greaterColor != null)
{
b = greaterColor;
}
if (percent * 100 < warningValue)
{
if (lessColor == null)
{
b = Brushes.Red;
}
else
{
b = lessColor;
}
}
e.Graphics.FillRectangle(b, rect);
}
static 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);
}
}
}
调用代码示例如下(绑定的数据源字段值为小于1的小数值,如:0.33,设置列的DisplayFormat属性):
gridView1.Columns["col11"].DisplayFormat.FormatType = FormatType.Numeric;
gridView1.Columns["col11"].DisplayFormat.FormatString = "p0";
CustomProgressBarColumn(gridView1, "col11", 50, Brushes.IndianRed, Brushes.DodgerBlue);