ListView自定义高亮显示选定行中的列

本文关键字:自定义 高亮 显示 ListView | 更新日期: 2023-09-27 18:28:53

我使用的ListView包含一些用户可以点击的子项(有些则不能)。这些对于每一行都是相同的。我用某种背景颜色标记这些可点击的子项目。

但是,当选择整行时(FullRowSelect=true),高亮显示会将相同的背景颜色设置为所有子项。

我想做的是向用户显示他选择了哪一行,但仍然保留子项的不同背景色。我玩了一些绘制ListView的所有者的游戏,但找不到这样做的方法。

谢谢你的帮助!Tom

ListView自定义高亮显示选定行中的列

您需要将ListView设置为OwnerDraw,并使用如下代码:

private void listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
    if ( e.SubItem.Name != "click1") e.DrawDefault = true; 
    else
    {
        if (e.Item.Selected)
              e.Graphics.FillRectangle(Brushes.SeaShell, 
                                       new Rectangle(e.Bounds.Location, e.Bounds.Size));
        else  e.Graphics.FillRectangle(Brushes.WhiteSmoke, 
                                       new Rectangle(e.Bounds.Location, e.Bounds.Size));
        e.DrawText();
    }
}
private void listView1_DrawColumnHeader(object sender, 
                                        DrawListViewColumnHeaderEventArgs e)
{
    e.DrawDefault = true;
}

显然,您不仅会调整两种颜色/画笔,还会调整的名称和可点击列的复选框。。(可能使用e.SubItem.Name.StartsWith("click_".)

请注意,您需要设置您希望看到的SubItemsNames可点击;eventParms中没有提供SubItemIndex。还要注意,您可能需要在代码中分配Name,即在创建/添加ListViewItem.ListViewSubItem时;我在设计师身上设定的名字不知怎么就没用了!还要注意,当您需要ListViewSubItem时,您需要如何对其进行资格鉴定!