问题
I have the following DataGridViewCheckBoxCell
. the problem is the visual update doesn't take place immediately in the edit mode, only when i quit it
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));
}
}
回答1:
You need 2 fixes:
You should create a
CustomDataGridViewCheckBoxColumn
as well which its cell template is set to yourCustomDataGridViewCheckBoxCell
.Instead of
FormattedValue
property, useformattedValue
parameter.
Here is the code:
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));
}
}
来源:https://stackoverflow.com/questions/46709110/custom-datagridviewcheckboxcell-visual-update-doesnt-work-in-edit-mode