ListBox 自动换行

ListBox Item自动换行


//设置属性
this.listMenuBox.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;

#region 绘制列表框

/// <summary>
/// 绘制每个 item(自动换行,不截断)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void listMenuBox_DrawItem(object sender, DrawItemEventArgs e)
{
    if (e.Index < 0 || e.Index >= listMenuBox.Items.Count) return;

    e.DrawBackground();

    string text = listMenuBox.Items[e.Index].ToString();
    if (string.IsNullOrEmpty(text)) return;

    // 背景色 - 选中时用系统高亮色
    if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
    {
        e.Graphics.FillRectangle(SystemBrushes.Highlight, e.Bounds);
    }
    else
    {
        e.Graphics.FillRectangle(Brushes.White, e.Bounds);
    }

    // 前景色
    Brush textBrush = (e.State & DrawItemState.Selected) == DrawItemState.Selected
        ? Brushes.White
        : Brushes.Black;

    // 绘制文本(自动换行,不截断)
    RectangleF rect = new RectangleF(
        e.Bounds.X + 2,
        e.Bounds.Y + 2,
        e.Bounds.Width - 4,
        e.Bounds.Height - 4
    );

    using (var sf = new StringFormat())
    {
        sf.FormatFlags = StringFormatFlags.LineLimit;
        // 去掉 Trimming,允许完整显示所有文本
        e.Graphics.DrawString(text, listMenuBox.Font, textBrush, rect, sf);
    }

    e.DrawFocusRectangle();
}
/// <summary>
/// 计算每个 item 的高度(支持自动换行)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void listMenuBox_MeasureItem(object sender, MeasureItemEventArgs e)
{
    if (e.Index < 0 || e.Index >= listMenuBox.Items.Count) return;

    string text = listMenuBox.Items[e.Index].ToString();
    if (string.IsNullOrEmpty(text))
    {
        e.ItemHeight = listMenuBox.Font.Height + 4;
        return;
    }

    // 计算文本在给定宽度下实际需要的高度
    using (var g = e.Graphics)
    {
        SizeF textSize = g.MeasureString(text, listMenuBox.Font,
            listMenuBox.ClientSize.Width - 8); // 减去边距
        e.ItemHeight = (int)Math.Ceiling(textSize.Height) + 4;
    }
}

#endregion
posted @ 2026-06-24 17:33  我本梁人  阅读(8)  评论(0)    收藏  举报