当我将鼠标悬停在列表框项目上时,如何更改它的背景颜色?
我已经用这段代码覆盖了 DrawItem 事件:
private void DrawListBox(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
Graphics g = e.Graphics;
Brush brush = ((e.State & DrawItemState.Selected) == DrawItemState.Selected) ?
new SolidBrush(Color.FromArgb(52, 146, 204)) : new SolidBrush(e.BackColor);
g.FillRectangle(brush, e.Bounds);
e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), e.Font,
new SolidBrush(e.ForeColor), e.Bounds, StringFormat.GenericDefault);
e.DrawFocusRectangle();
}
但是,ListBox 没有包含悬停项的属性。也没有像 MouseEnterItem、MouseHoverItem 事件或 ListBox 上的任何类似事件可供订阅。
我做了很多研究,但我发现的只是一个关于 SO 的类似问题,它混淆了 ListBox 和 ListView:Hightlight Listbox item on mouse over event
请您参考如下方法:
由于 ListBox 不提供 MouseEnterItem 和 MouseHoverItem 事件,因此有必要自己编写此功能,跟踪鼠标的坐标以确定鼠标悬停在哪个项目上。
下面的问题非常相似,目的是在悬停时显示每个项目的工具提示。 Michael Lang 的回答是一个很好的解决方法,应该适合您的目的:
How can I set different Tooltip text for each item in a listbox?
