在 C# WinForm 中,可以使用 ListView 控件来显示数据。要实现隔行用不同颜色显示,可以在 ListView 的 DrawItem 事件中进行处理。

以下是示例代码:

private void listView1_DrawItem(object sender, DrawListViewItemEventArgs e)
{
    // 设置奇数行的背景颜色
    if (e.ItemIndex % 2 == 1)
    {
        e.Item.BackColor = Color.LightGray;
    }
    else
    {
        e.Item.BackColor = Color.White;
    }
}

private void listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
    // 设置选中行的背景颜色
    if ((e.ItemState & ListViewItemStates.Selected) == ListViewItemStates.Selected)
    {
        e.SubItem.BackColor = Color.Yellow;
    }
    else
    {
        e.SubItem.BackColor = e.Item.BackColor;
    }
}

private void listView1_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
{
    // 不需要处理
}

在上述代码中,DrawItem 事件处理了 ListView 的每一行的背景颜色。如果是奇数行,背景颜色设置为灰色,否则设置为白色。

DrawSubItem 事件处理了 ListView 的每一行中的子项的背景颜色。如果是选中的行,背景颜色设置为黄色,否则设置为当前行的背景颜色。

DrawColumnHeader 事件处理 ListView 的列头,但在此示例中不需要进行处理。

要使用上述代码,只需将 DrawItem、DrawSubItem 和 DrawColumnHeader 事件绑定到 ListView 控件,并在 Form_Load 事件中添加以下代码:

listView1.FullRowSelect = true;
listView1.OwnerDraw = true;

设置 FullRowSelect 属性为 true 可以使得选中行时选中整行。设置 OwnerDraw 属性为 true 可以启用自定义绘制。

C# winform listview 控件隔行用不同颜色显示选中行用第三种颜色显示

原文地址: https://www.cveoy.top/t/topic/brlL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录