gpt4 book ai didi

c# - DGV CellPainting 行为异常

转载 作者:太空宇宙 更新时间:2023-11-03 11:10:48 24 4
gpt4 key购买 nike

我在 DataGridView 中显示一个小时列表,并想用阴影显示那些不属于营业时间的时间。我正在尝试使用 CellPainting 来执行此操作,但是我得到了奇怪的结果。有人可以解释一下我在这里做错了什么吗?

private void dgvItemView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
switch (_formType)
{
case FormType.DayView:
TimeSpan openTime = iFlow.Properties.Settings.Default.BusinessHourOpen;
TimeSpan closeTime = iFlow.Properties.Settings.Default.BusinessHourClose;

DataGridViewCell cell = this.dgvItemView[e.ColumnIndex, e.RowIndex];

if (cell.RowIndex < openTime.Hours || cell.RowIndex > closeTime.Hours)
{
e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(25, Color.Red)), e.ClipBounds);
}
break;
}
}

但是这段代码会产生渐变效果,如下:

Form

我真的不明白。当我上下滚动时,阴影也会消失并重新出现,具体取决于我滚动的程度。

那么有人可以解释一下我在这里做错了什么吗?我还需要绘制部分块,以防营业时间不准时,例如08:45 到 17:30,所以我不能只更改单元格的背景颜色来实现此目的。

最佳答案

e.ClipBounds 指的是 DataGridView 的整个可见部分。
实际上,您所做的是在整个可见 DataGridView 区域上绘制多个透明层,从而在您滚动时产生渐变效果。

您应该改用 e.CellBounds

另一个与您的问题无关的问题是您正在从 SolidBrush 泄漏 GDI 句柄。绘制后 SolidBrushDispose(),或者更好的是,使用这样的 using 语句:

using (var sb = new SolidBrush(Color.FromArgb(25, Color.Red)))
{
e.Graphics.FillRectangle(sb , e.CellBounds);
}

编辑:

您还必须在绘画后将 e.Handled 设置为 true,以防止系统在您的作品上绘画。

来自 MSDN :

If you manually paint the cell, set the HandledEventArgs.Handled property to true. If you do not set HandledEventArgs.Handled to true, the cell will paint over your customizations.

关于c# - DGV CellPainting 行为异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14112849/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com