我有以下DataGridViewCheckBoxCell
. 问题是视觉更新不会在编辑模式下立即发生,只有当我退出它时才会
public class CustomDataGridViewCell : DataGridViewCheckBoxCell
{
protected override void Paint(Graphics graphics,
Rectangle clipBounds, Rectangle cellBounds, int rowIndex,
DataGridViewElementStates elementState, object value,
object formattedValue, string errorText,
DataGridViewCellStyle cellStyle,
DataGridViewAdvancedBorderStyle advancedBorderStyle,
DataGridViewPaintParts paintParts)
{
base.Paint(graphics, clipBounds, cellBounds, rowIndex,
elementState, value, formattedValue, errorText, cellStyle,
advancedBorderStyle, DataGridViewPaintParts.All & ~DataGridViewPaintParts.ContentForeground);
var val = (bool?)FormattedValue;
var img = val.HasValue && val.Value ? Properties.Resources._checked : Properties.Resources._unchecked;
var w = img.Width;
var h = img.Height;
var x = cellBounds.Left + (cellBounds.Width - w) / 2;
var y = cellBounds.Top + (cellBounds.Height - h) / 2;
graphics.DrawImage(img, new Rectangle(x, y, w, h));
}
}
您需要 2 个修复:
-
您还应该创建一个
CustomDataGridViewCheckBoxColumn
,其单元格模板设置为您的CustomDataGridViewCheckBoxCell
。 -
不要使用
FormattedValue
属性,而是使用formattedValue
参数。
这是代码:
public class CustomDataGridViewCheckBoxColumn: DataGridViewCheckBoxColumn
{
public CustomDataGridViewColumn()
{
this.CellTemplate = new CustomDataGridViewCheckBoxCell();
}
}
public class CustomDataGridViewCheckBoxCell: DataGridViewCheckBoxCell
{
protected override void Paint(Graphics graphics,
Rectangle clipBounds, Rectangle cellBounds, int rowIndex,
DataGridViewElementStates elementState, object value,
object formattedValue, string errorText,
DataGridViewCellStyle cellStyle,
DataGridViewAdvancedBorderStyle advancedBorderStyle,
DataGridViewPaintParts paintParts)
{
base.Paint(graphics, clipBounds, cellBounds, rowIndex,
elementState, value, formattedValue, errorText, cellStyle,
advancedBorderStyle, DataGridViewPaintParts.All & ~DataGridViewPaintParts.ContentForeground);
var val = (bool?)formattedValue;
var img = val.HasValue && val.Value ? Properties.Resources.Checked : Properties.Resources.UnChecked;
var w = img.Width;
var h = img.Height;
var x = cellBounds.Left + (cellBounds.Width - w) / 2;
var y = cellBounds.Top + (cellBounds.Height - h) / 2;
graphics.DrawImage(img, new Rectangle(x, y, w, h));
}
}