У меня есть список объектов (типа 'TrackedSet'), который является данными, привязанными к DataGridView. Когда добавляется новая строка, я хочу иметь возможность изменять внешний вид строки на основе свойства объекта, связанного с данными.
Я могу нарисовать собственный фон строки в событии RowPrePaint, но я изо всех сил пытаюсь изменить цвет переднего ряда для строки.
Исходя из приведенного ниже кода, я меняю это, постоянно меняя свойство DefaultCellStyle для строки на предопределенный стиль ячейки, для которого передний цвет имеет желаемое значение.
Это правильно? Это кажется неуклюжим и просто неправильно.
Любой совет приветствуется.
/// <summary>
/// Handles the drawing of each DataGridView row depending on TrackedSet error or flagged state.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void setLogDataGridView_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
if ((e.State & DataGridViewElementStates.Displayed) == DataGridViewElementStates.Displayed)
{
// Always disable normal painting of selection background and focus.
e.PaintParts &= ~(DataGridViewPaintParts.SelectionBackground |
DataGridViewPaintParts.Focus);
// Get the tracked set associated with the row being painted.
TrackedSet set = this._setLogBindingSource[e.RowIndex] as TrackedSet;
if (set.IsFlagged || set.IsError) // Row requires custom painting.
{
Color backColour1 = Color.Empty;
Color backColour2 = Color.Empty;
// Get rectangle of area to paint with custom brush.
Rectangle rowBounds = new Rectangle(
e.RowBounds.Left + 1, // Location x
e.RowBounds.Top, // Location y
this.setLogDataGridView.Columns.GetColumnsWidth(
DataGridViewElementStates.Visible) -
this.setLogDataGridView.HorizontalScrollingOffset + 1, // Width
e.RowBounds.Height); // Height
// Disable painting of backgrounds when custom painting row.
e.PaintParts &= ~(DataGridViewPaintParts.Background |
DataGridViewPaintParts.ContentBackground);
if (set.IsFlagged) // Highlight colour.
{
backColour1 = this._highlightBackColour1;
backColour2 = this._highlightBackColour2;
this.setLogDataGridView.Rows[e.RowIndex].DefaultCellStyle = this._highlightStyle;
}
else // Error colour.
{
backColour1 = this._errorBackColour1;
backColour2 = this._errorBackColour2;
this.setLogDataGridView.Rows[e.RowIndex].DefaultCellStyle = this._errorStyle;
}
// Paint the custom background.
using (Brush lgb = new LinearGradientBrush(rowBounds, backColour1, backColour2, LinearGradientMode.Vertical))
{
e.Graphics.FillRectangle(lgb, rowBounds);
}
}
}
}