【问题标题】:How to change DataGridView cell image on mouseover?如何在鼠标悬停时更改 DataGridView 单元格图像?
【发布时间】:2016-09-16 00:44:54
【问题描述】:

我正在 datagridviews 列单元格中绘制图像,如下所示:

Private Sub dataGridView1_CellPainting(sender As Object, e As DataGridViewCellPaintingEventArgs) Handles DataGridView1.CellPainting
    If e.ColumnIndex = 20 AndAlso e.RowIndex >= 0 Then

        If String.IsNullOrEmpty(e.Value.ToString) Then

            e.Paint(e.CellBounds, DataGridViewPaintParts.All)
            Dim img As Image = Image.FromFile("C:\Users\me\Desktop\glass.png")
            e.Graphics.DrawImage(img, e.CellBounds.Left + 10, e.CellBounds.Top + 5, 25, 25)
            e.Handled = True
        End If

    End If
End Sub

如果我将鼠标悬停在其中一个单元格上(仅针对悬停的单元格而不是所有单元格),是否可以将图像切换到另一个?

【问题讨论】:

  • CellEnter(有短暂的延迟?)然后 CellLeave 撤消。不相关,但如果您显示相同的图像或一小组图像,您应该将它们加载到数组或列表中,而不是每次都创建一个新的。每个单元格都需要自己的 glass.png 个人副本,您不必担心处理它们。
  • 好的,谢谢。所以我假设细胞涂料在进入和离开时会重新发射?
  • 不,这不起作用 - 当您激活单元格时会触发。抱歉,我更关注其他花絮
  • CellMouseLeave 和 CellMouseEnter 是我的想法。哎呀.... ^ Every cell does **not** need its own personal copy...
  • 您能否详细说明将它们加载到数组中的含义?你的意思是不是从文件加载?希望尽可能地优化它。

标签: .net vb.net datagridview


【解决方案1】:

首先,您的代码为要显示该图像的每个单元格创建一个新图像。每个单元格实际上并不需要自己的个人图像对象。

此外,您可以将图像添加到资源中,而不是从磁盘加载(这意味着可以删除或移动文件)。从那里获取它仍然每次都会创建一个新的图像对象,因此将它们存储在一个数组中:

Private ImgBalls As Image()

然后是 FormLoad 之类的地方:

' ToDo: add a BulletColor enum for indexing
ImgBalls = New Image() {
                        My.Resources.ballblack, My.Resources.ballblue,
                        My.Resources.ballgreen, My.Resources.ballorange,
                        My.Resources.ballred, My.Resources.ballpurple,
                        My.Resources.ballyellow
                        }

然后使用它像悬停(没有延迟):

Private Sub dgv1_CellMouseEnter(etc etc etc...
    If e.RowIndex < 0 OrElse dgv1.Rows(e.RowIndex).IsNewRow Then Return

    If e.ColumnIndex = 5 Then
        dgv1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = ImgBalls(6)
    End If
End Sub

Private Sub dgv1_CellMouseLeave(etc etc etc...
    If e.RowIndex < 0 OrElse dgv1.Rows(e.RowIndex).IsNewRow Then Return

    If e.ColumnIndex = 5 Then
        dgv1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = ImgBalls(0)
    End If
End Sub

这会在鼠标悬停时将默认的黑色项目符号更改为黄色:

请注意,如果空值无效,您也可以使用CellErrorText 提供红色感叹号和一些文本,而不是图像。

【讨论】:

  • 看起来正是我想要完成的,但找不到太多信息。感谢您抽出宝贵时间提供帮助,非常感谢!
  • 所有行都使用相同的黑色子弹图像和相同的黄色子弹图像。
  • 您可以通过在 CellMouseEnter 中设置标志并启动计时器来实现标准的 400 毫秒悬停延迟,然后在 CellMouseMove 中实际设置图像。这和真正的悬停之间的 ~400 毫秒差异似乎有点矫枉过正
猜你喜欢
  • 2015-09-29
  • 2012-06-24
  • 1970-01-01
  • 2016-08-05
  • 2022-01-19
  • 1970-01-01
  • 2010-11-30
相关资源
最近更新 更多