C# DataGridViewButtonColumn充当DataGridViewCheckBoxColumn

C# DataGridViewButtonColumn充当DataGridViewCheckBoxColumn,c#,.net,winforms,datagridview,datagridviewcolumn,C#,.net,Winforms,Datagridview,Datagridviewcolumn,我想让DataGridViewButtonColumn充当DataGridViewCheckBoxColumn。这意味着按钮中的某个图像为true,另一个图像为false,并通过DataMember绑定到属性。 我认为继承自DataGridViewCheckBoxColumn和重写paint方法的类“应该”工作。只需使用DataGridViewCheckBoxColumn但处理DataGridView的CellPaint事件,并为选中状态绘制一个图像,为未选中状态绘制另一个图像 示例 创建名为F

我想让
DataGridViewButtonColumn
充当
DataGridViewCheckBoxColumn
。这意味着按钮中的某个图像为
true
,另一个图像为
false
,并通过
DataMember
绑定到属性。
我认为继承自
DataGridViewCheckBoxColumn
重写
paint
方法的类“应该”工作。

只需使用
DataGridViewCheckBoxColumn
但处理
DataGridView
CellPaint
事件,并为选中状态绘制一个图像,为未选中状态绘制另一个图像

示例

创建名为
Form1
表单
,然后在表单上放置
DataGridView
控件,并用以下代码替换
Form1.cs
的内容。还要确保已将
选中的
未选中的
图像添加到
资源

然后你会看到这样的结果:


那么你的问题是什么?你试过什么了?到目前为止,我还停留在绘画方法上。不知道该怎么办不需要继承任何东西。只需使用网格的CellPainting事件。@ihisham您是否尝试了解如何在winforms中绘制图像?快速问题我将代码移动到独立的DataGridViewColumn,以便可以自由使用它。它正在工作,但是当我处于编辑模式时,我没有得到视觉更新,更新只有在我退出时才生效。知道为什么吗?你确定你是从
DataGridViewCheckBoxColumn
派生的吗?嗯,也许发布一个包含您创建的自定义列代码的新问题会更好
public Form1()
{
    InitializeComponent();
    this.Load += Form1_Load;
    this.dataGridView1.CellPainting += dataGridView1_CellPainting;
}
private void Form1_Load(object sender, EventArgs e)
{
    var dt = new DataTable();
    dt.Columns.Add("Column1", typeof(bool));
    dt.Rows.Add(false);
    dt.Rows.Add(true);
    this.dataGridView1.DataSource = dt;
}
void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    if (e.ColumnIndex == 0 && e.RowIndex >= 0)
    {
        var value = (bool?)e.FormattedValue;
        e.Paint(e.CellBounds, DataGridViewPaintParts.All &
                                ~DataGridViewPaintParts.ContentForeground);
        var img = value.HasValue && value.Value ?
            Properties.Resources.Checked : Properties.Resources.UnChecked;
        var size = img.Size;
        var location = new Point((e.CellBounds.Width - size.Width) / 2,
                                    (e.CellBounds.Height - size.Height) / 2);
        location.Offset(e.CellBounds.Location);
        e.Graphics.DrawImage(img, location);
        e.Handled = true;
    }
}