下列代码演示了如何使用 CustomDrawCell 事件来设置 “UnitsInStock” 列单元格的外观。 如果单元格属于获得焦点的行,则不执行自定义绘制,而使用默认设置绘制。 否则,根据单元格的取值绘制它的背景。
如果相同行的 “Discontinued” 列单元格被勾选,则也不执行自定义绘制单元格。 而只是把 DisplayText 参数设置为“Discontinued”文本,并保持 Handled 参数被设置为 false。 在事件处理程序执行完毕之后,将使用默认的外观设置绘制此文本。
如果“Discontinued” 列的取值被设置为 false,则相同行的“UnitsInStock” 单元格的背景根据单元格的取值使用 LightSkyBlue 或 “LightGreen” 颜色被绘制。 在这种情况下,为了阻止默认的单元格绘制,Handled 参数被设置为 true。
C# | 复制代码 |
---|---|
using DevExpress.XtraGrid.Views.Grid; using DevExpress.XtraGrid.Views.Base; private void advBandedGridView1_CustomDrawCell(object sender, RowCellCustomDrawEventArgs e) { GridView currentView = sender as GridView; if(e.RowHandle == currentView.FocusedRowHandle) return; Rectangle r = e.Bounds; if(e.Column.FieldName == "UnitsInStock") { bool check = (bool)currentView.GetRowCellValue(e.RowHandle, currentView.Columns["Discontinued"]); if(check) { //Change the text to display //The e.Handled parameter is false //So the cell will be painted using the default appearance settings e.DisplayText = "Discontinued"; } else { // If the cell value is greater then 50 the paint color is LightGreen, // otherwise LightSkyBlue Brush ellipseBrush = Brushes.LightSkyBlue; if (Convert.ToInt16(e.CellValue) > 50) ellipseBrush = Brushes.LightGreen; //Draw an ellipse within the cell e.Graphics.FillEllipse(ellipseBrush, r); r.Width -= 12; //Draw the cell value e.Appearance.DrawString(e.Cache, e.DisplayText, r); //Set e.Handled to true to prevent default painting e.Handled = true; } } } |
Visual Basic | 复制代码 |
---|---|
Imports DevExpress.XtraGrid.Views.Base Imports DevExpress.XtraGrid.Views.Grid Private Sub advBandedGridView1_CustomDrawCell(ByVal sender As Object, _ ByVal e As RowCellCustomDrawEventArgs) Handles advBandedGridView1.CustomDrawCell Dim currentView As GridView = CType(sender, GridView) If (e.RowHandle = currentView.FocusedRowHandle) Then Return Dim r As Rectangle = e.Bounds If e.Column.FieldName = "UnitsInStock" Then Dim check As Boolean = CType(currentView.GetRowCellValue(e.RowHandle, _ currentView.Columns("Discontinued")), Boolean) If check Then 'Change the text to display 'The e.Handled parameter is false 'So the cell will be painted using the default appearance settings e.DisplayText = "Discontinued" Else 'If the cell value is greater then 50 the paint color is LightGreen, ' otherwise LightSkyBlue Dim ellipseBrush As Brush = Brushes.LightSkyBlue If e.CellValue > 50 Then ellipseBrush = Brushes.LightGreen 'Draw an ellipse within the cell e.Graphics.FillEllipse(ellipseBrush, r) r.Width -= 12 'Draw the cell value e.Appearance.DrawString(e.Cache, e.DisplayText, r) 'Set e.Handled to true to prevent default painting e.Handled = True End If End If End Sub |