Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
395 views
in Technique[技术] by (71.8m points)

c# - How to add multiline Text to a ListBox item?

I have a little problem and can't find a solution.
I would like to put a text at the end of a ListBox item and I have no idea how...

TagLib.File f = TagLib.File.Create(paths[i]);
listBox1.Items.Add("0" + i + ". " + f.Tag.Title +"
" + string.Join(", ", f.Tag.Performers) + " - " + "
" + f.Tag.Album + "                                               "  + f.Properties.Duration.TotalMinutes.ToString());

I've already tried it but unfortunately it doesn't work that way. Maybe someone knows how you can always put the text at the end, with a code?

I want the text of all items to match I want the text of all items to match each other And I can't find a solution how to put the text at the end and how the text can match each other And I can't find a solution how to put the text at the end and how the text can match each other

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To add multiline text to a ListBox Control, you need to measure and draw the text yourself.

Set the ListBox.DrawMode to DrawMode.OwnerDrawVariable, then override OnMeasureItem and OnDrawItem.

OnMeasureItem is called before an Item is drawn, to allow to define the Item Size, setting the MeasureItemEventArgs e.ItemWidth and e.ItemHeight properties (you have to verify that the ListBox contains Items before trying to measure one).

→ When OnDrawItem is called, the e.Bounds property of its DrawItemEventArgs will be set to the measure specified in OnMeasureItem.

To measure the Text, you can use both the TextRenderer class MeasureText() method or Graphics.MeasureString. The former is preferred, since we're going to use the TextRenderer class to draw the Items' text: TextRenderer.DrawText is more predictable than Graphics.DrawString() in this context and it renders the text naturally (as the ListBox - or ListView - does).

The TextRenderer's TextFormatFlags are used to fine-tune the rendering behavior. I've added TextFormatFlags.ExpandTabs to the flags, so you can also add Tabs ("") to the Text when needed. See the visual example.
" " can be used to generate line feeds.

In the sample code, I'm adding 8 pixels to the measured height of the Items, since a line separator is also drawn to better define the limits of an Item (otherwise, when a Item spans more than one line, it may be difficult to understand where its text starts and ends).

? Important: the maximum Item.Height is 255 pixels. Beyond this measure, the Item's text may not be rendered or be rendered partially (but it usually just disappears). There's a Min/Max check on the item height in the sample code.

This is how it works:

ListBox OwnerDrawn Multiline

I suggest to use a class object, if you haven't, to store your Items and describe them. Then use a List<class> as the ListBox.DataSource. This way, you can better define how each part should be rendered. Some parts may use a Bold Font or a different Color.

using System;
using System.Drawing;
using System.Windows.Forms;

public class ListBoxMultiline : ListBox
{
    TextFormatFlags flags = TextFormatFlags.WordBreak |
                            TextFormatFlags.PreserveGraphicsClipping |
                            TextFormatFlags.LeftAndRightPadding |
                            TextFormatFlags.ExpandTabs |
                            TextFormatFlags.VerticalCenter;

    public ListBoxMultiline() { this.DrawMode = DrawMode.OwnerDrawVariable; }

    protected override void OnDrawItem(DrawItemEventArgs e)
    {
        if (Items.Count == 0) return;
        if (e.State.HasFlag(DrawItemState.Focus) || e.State.HasFlag(DrawItemState.Selected)) {
            using (var selectionBrush = new SolidBrush(Color.Orange)) {
                e.Graphics.FillRectangle(selectionBrush, e.Bounds);
            }
        }
        else {
            e.DrawBackground();
        }
        
        TextRenderer.DrawText(e.Graphics, GetItemText(Items[e.Index]), Font, e.Bounds, ForeColor, flags);

        if (e.Index != Items.Count - 1) {
            Point lineOffsetStart = new Point(e.Bounds.X, e.Bounds.Bottom - 1);
            Point lineOffsetEnd = new Point(e.Bounds.Right, e.Bounds.Bottom - 1);
            e.Graphics.DrawLine(Pens.LightGray, lineOffsetStart, lineOffsetEnd);
        }
        base.OnDrawItem(e);
    }

    protected override void OnMeasureItem(MeasureItemEventArgs e)
    {
        if (Items.Count == 0) return;
        var size = GetItemSize(e.Graphics, GetItemText(Items[e.Index]));
        e.ItemWidth = size.Width;
        e.ItemHeight = size.Height;
        base.OnMeasureItem(e);
    }

    private Size GetItemSize(Graphics g, string itemText)
    {
        var size = TextRenderer.MeasureText(g, itemText, Font, ClientSize, flags);
        size.Height = Math.Max(Math.Min(size.Height, 247), Font.Height + 8) + 8;
        return size;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...