2

我在 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;
    }
}

但是,此代码会产生渐变效果,如下所示:

形式

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

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

4

1 回答 1

2

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

你应该e.CellBounds改用。

与您的问题无关的另一个问题是您正在从SolidBrush. Dispose()你的SolidBrush画后,或者更好的是,使用using这样的声明:

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

编辑:

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

来自MSDN

如果您手动绘制单元格,请将 HandledEventArgs.Handled 属性设置为 true。如果未将 HandledEventArgs.Handled 设置为 true,则单元格将覆盖您的自定义设置。

于 2013-01-01T18:13:25.690 回答