C#Listbox.DrawItem以色行各 [英] C# Listbox.DrawItem to color each lines

查看:345
本文介绍了C#Listbox.DrawItem以色行各的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码改变是如何列表框的行为。我可以改变文本的颜色,但我无法改变每一行的背景颜色。

I have some code to change how listbox act. I can change the color of text, but I am unable to change the color of the background of each line.

这是一个循环,每我行

LBLines是字符串存储在一个全局变量

LBLines is an array of string store in a global variable

if (LBLines[e.Index] != "None")
{
       e.Graphics.FillRectangle(new SolidBrush(Color.FromName(LBLines[e.Index])),
e.Bounds.X,e.Bounds.Y,e.Bounds.Width,e.Bounds.Height);
}

这将颜色相同的颜色的每一个线条,甚至那些被列为无你是我需要的是他们保持相同的颜色作为默认的背景颜色

This will color EVERY lines of the same color, even those listed as "None", thou what I need is that they stay same color as default background color.

编辑:Comparaison不是问题,问题来自e.Graphics.FillRectangle。它似乎颜色的所有行的空间,无论一个我画的。

Comparaison is not the problem, problem come from the e.Graphics.FillRectangle. It seems to color ALL the lines spaces, regardless of the one I am drawing.

EDIT2:修改后的代码表明h后等于e.Index

Modified code to show that h was equal to e.Index

推荐答案

硬盘周围没有你的代码(循环的方法,...)更多的上下文的说法,但是这个代码做什么,我想这是你想要的:

Hard to say without more context around your code (the loop, the method,...), but this code does what I think it is you want:

public partial class Form1 : Form
{
    string[] Colors { get; set; }

    public Form1()
    {
        InitializeComponent();
        Colors = new string[] { "red", "blue", "white", "none", "orange" };
        listBox1.Items.AddRange(Colors);
    }

    private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
    {
        e.DrawBackground();
        if (Colors[e.Index] != "none")
        {
            using (var brush = new SolidBrush(Color.FromName(Colors[e.Index])))
            {
                e.Graphics.FillRectangle(brush, e.Bounds);
            }
        }
        e.Graphics.DrawString(Colors[e.Index], Font, SystemBrushes.ControlText, e.Bounds);
    }
}



请注意, DrawStyle 的ListBox 设置为 OwnerDrawFixed

这篇关于C#Listbox.DrawItem以色行各的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆