首页 > 解决方案 > 如何在winfoms中更改列表视图的选定行背景

问题描述

如果行中的数字为 0,我想更改所选行的背景。我尝试关注但对我不起作用。

list.SelectedItems[0].BackColor = Color.Red;

标签: c#winforms

解决方案


据我所知,ListView使用windows的默认设计颜色作为选择颜色,所以如果你想改变它,你必须自己绘制项目。

您可以通过将 ListView 的“OwnerDraw”属性设置为 true 并为 ListView 的“DrawItem”事件编写自己的逻辑来做到这一点。

所以是这样的:

private void listView1_DrawItem(object sender, DrawListViewItemEventArgs e)
{
    if (e.Item.Selected)
    {
        if (e.Item.Index == 0)
        {
            e.Graphics.FillRectangle(Brushes.Red, e.Bounds);
        }
        else
        {
            e.Graphics.FillRectangle(SystemBrushes.Highlight, e.Bounds);
        }                       
    }
    else
    {
        e.Graphics.FillRectangle(Brushes.White, e.Bounds);
    }

    e.DrawText(TextFormatFlags.TextBoxControl);
}     

推荐阅读