简体   繁体   中英

How can i color part of item string in listView?

For example if in a listView I have the item:

Hello world

Then I want that Hello will be in red and world in green

In the top of the form I did

listView1.OwnerDraw = true;

In the designer I created listView draw item event:

private void listView1_DrawItem(object sender, DrawListViewItemEventArgs e) {
    e.DrawBackground();
    e.DrawFocusRectangle();
}

What should I do from here? What I want to do is to add in Red color a word to each item from it's left side for example:

`Hello world`

So world Hello world

So the first world on the left will be in red on this part. I want to add this to every item.

One way to achieve it is through ListBox.DrawItem Event . You can customize rendering of your strings in listbox in this function.

Add a new handler for that event:

listBox1.DrawMode = DrawMode.OwnerDrawFixed;
listBox1.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.listBox1_DrawItem);

And do rendering of texts in listbox :

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    e.DrawBackground();
    e.DrawFocusRectangle();

    var itemStr = listBox1.Items[e.Index].ToString();
    var strings = itemStr.Split(' '); // Here I split item text
    var bound = e.Bounds;

    foreach (var s in strings)
    {
        var strRenderLegnth = e.Graphics.MeasureString(s, new Font(FontFamily.GenericSansSerif, 10)).Width;

        e.Graphics.DrawString // Draw each substring with customized settings
        (
            s,
            new Font(FontFamily.GenericSansSerif, 10),
            new SolidBrush(Color.Red), // Use verius colors for each substring
            bound
        );

        bound = new Rectangle(e.Bounds.X + (int)strRenderLegnth, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM