【发布时间】:2019-04-03 12:18:08
【问题描述】:
我正在尝试更改 ListView 中选择栏的默认(蓝色)颜色。
我拒绝使用 ObjectListView,因为我必须更改所有代码。
我已经搜索过这个主题并在这里找到了一些答案:
Change background selection color of ListView?
但这指向 ObjectListView。
当我之前使用 ListBox 时,这可以根据我的喜好设置选择栏颜色:
- 在属性下将DrawMode设置为
OwnerDrawFixed - 在事件下将 DrawItem 设置为
ListBox1_DrawItem
private void ListBox1_DrawItem(object sender, DrawItemEventArgs e)
{
if (e.Index < 0) return;
//if the item state is selected them change the back color
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
e = new DrawItemEventArgs(e.Graphics,
e.Font,
e.Bounds,
e.Index,
e.State ^ DrawItemState.Selected,
e.ForeColor,
Color.FromArgb(43, 144, 188));//Choose the color
// Draw the background of the ListBox control for each item.
e.DrawBackground();
// Draw the current item text
e.Graphics.DrawString(lb_result.Items[e.Index].ToString(), e.Font, Brushes.Black, e.Bounds, StringFormat.GenericDefault);
// If the ListBox has focus, draw a focus rectangle around the selected item.
e.DrawFocusRectangle();
}
但我现在使用的是 ListView。
- 我将
OwnerDraw设置为True - 我将 DrawItem 设置为
ListView1_DrawItem
...并使用上面的代码。
我希望它会显示不同的选择颜色,但我得到了一些错误:
如何将这段代码正确地用于 ListView?
【问题讨论】:
-
您只需要:
if (e.Item.Selected) =>绘制背景 (e.Graphics.FillRectangle()) 和文本。如果未选中,e.DrawDefault = true;。您可以使用e.Bounds度量值填充矩形,使用您想要的任何颜色。如果 ListView 包含任何位图,您还需要绘制位图。 -
@Jimi 你能给我看一下代码示例吗?我正在尝试,但没有做对。
标签: c# winforms listview colors selection