c#自定义列表框项目,不使用水平滚动的自动换行

时间:2018-03-17 14:00:48

标签: c# winforms

所以我在C#windows窗体中创建了一个自定义列表框。但它正在包装它所持有的文本,而不是显示我想要的水平滚动条。

以下代码适用于列表框:

public class MyList : ListBox
{
    public MyList()
    {
        base.ItemHeight = 20;
        base.DrawMode = DrawMode.OwnerDrawFixed;
        HorizontalScrollbar = true;
    }

    protected override void OnDrawItem(DrawItemEventArgs e)
    {
        e.DrawBackground();
        if (e.State == DrawItemState.Focus)
            e.DrawFocusRectangle();
        int index = e.Index;
        if (index < 0 || index >= Items.Count) return;
        var item = Items[index];
        string text = (item == null) ? "(null)" : item.ToString();


            e.DrawBackground();
            Graphics g = e.Graphics;
            g.FillRectangle(new SolidBrush(Color.Transparent), e.Bounds);


        using (var brush = new SolidBrush(e.ForeColor))
        {
            e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
            e.Graphics.DrawString(text, e.Font, brush, e.Bounds);
        }
    }
}

我很确定它与e.Bounds有关,但我不确定如何设置“无限”值并启用滚动。

编辑:在构造函数中,我确实有HorizontalScrollbar = true但它仍然没有显示它。我想我需要修改e.Bounds

谢谢大家。

1 个答案:

答案 0 :(得分:0)

好。想出来了。

您必须衡量string所持有的项目的listbox长度,然后将其与listBox.HorizontalExtent进行比较,如果更高,则将该值设为新的HorizontalExtent。要绘制文本而不进行包装,您只需将宽度参数传递给它。只是一个职位。

代码:

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
    {
        e.DrawBackground();
        if (e.State == DrawItemState.Focus)
            e.DrawFocusRectangle();
        int index = e.Index;
        if (index < 0 || index >= listBox1.Items.Count) return;
        var item = listBox1.Items[index];
        string text = (item == null) ? "(null)" : item.ToString();
        int newHE = (int)(e.Graphics.MeasureString(text, e.Font).Width + 2);
        if (listBox1.HorizontalExtent < newHE)
        {
            listBox1.HorizontalExtent = newHE;
        }
        using (var brush = new SolidBrush(e.ForeColor))
        {
            e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
            e.Graphics.DrawString(text, e.Font, brush, 0f, e.Bounds.Top + 3); //I do +3 because I wanted to shimmy the text down a bit from the top
        }
    }