自定义数据网格视图复选框单元格视觉对象更新在编辑模式下不起作用



我有以下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 个修复:

  1. 您还应该创建一个CustomDataGridViewCheckBoxColumn,其单元格模板设置为您的CustomDataGridViewCheckBoxCell

  2. 不要使用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));
    }
}

最新更新