自定义DataGridViewCheckBoxCell可视化更新不能在编辑模式下工作
问题描述:
我有以下DataGridViewCheckBoxCell
。问题是,当我离开它自定义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));
}
}
没错这是FormattedValue的参数问题。我感到尴尬*叹* – ihisham