DataGridViewButtonColumn充当DataGridViewCheckBoxColumn
我想要DataGridViewButtonColumn
充当DataGridViewCheckBoxColumn
。意思是在按钮内部有一些图像作为true
,另一图像为false
,并通过DataMember
绑定到属性。 我认为一个类继承DataGridViewCheckBoxColumn
和override
paint
方法“应该”的工作。DataGridViewButtonColumn充当DataGridViewCheckBoxColumn
只要使用DataGridViewCheckBoxColumn
,但处理CellPaint
事件DataGridView
并绘制一个图像检查状态和另一个未选中状态。
例
创建一个名为Form
Form1
再滴上形成DataGridView
控制,并用下面的代码替换的Form1.cs
内容。还请确保您将Checked
和
UnChecked
图像添加到
Resources
。
然后你会看到这样的结果:
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;
}
}
快速问题我将代码移到了独立的DataGridViewColumn中,所以我可以自由使用它。它的工作,但我没有得到视觉更新,当我在编辑模式下,只有当我退出更新才会生效。任何想法为什么? – ihisham
你确定你是从'DataGridViewCheckBoxColumn'派生的吗?嗯,也许最好发布一个包含您创建的自定义列的代码的新问题。 –
在这里我发布的代码使用的问题https://stackoverflow.com/questions/46709110/custom-datagridviewcheckboxcell-visual-update-doesnt-work-in-edit-mode – ihisham
那么什么是你的问题?你有什么尝试? –
到目前为止我卡在涂料的方法。不知道该怎么办 – ihisham
不需要继承任何东西。只需使用网格的CellPainting事件。 – LarsTech