当我将鼠标悬停在列表框项目上时,如何更改其背景颜色?
我已经用以下代码覆盖了 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 Event 或任何类似的事件可供订阅。
我做了很多研究,但我发现的只是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?
关于c# - 如何在悬停时更改列表框项目的背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27605557/