如何使标签控件截断带有省略号的长字符串?

Mic*_*elB 10 .net label winforms

我有一个更改文本的标签,我希望它是一个固定长度的单行.每当文本比标签长度长时,我希望它在最后显示与"..."匹配的任何内容.例如:

Some Very Long Text
Run Code Online (Sandbox Code Playgroud)

看起来像:

Some Very Lon...
Run Code Online (Sandbox Code Playgroud)

有谁知道这是怎么做到的吗?

def*_*ale 16

其中一个选项是将Label.AutoEllipsis设置为true.

将AutoEllipsis设置为true可在用户使用鼠标移动控件时显示超出Label宽度的文本.如果AutoSize为true,则标签将增长以适合文本,并且不会显示省略号.

所以,你需要设置AutoSize为false.省略号外观取决于标签的固定宽度.AFAIK,您需要手动处理文本更改以使其依赖于文本长度.

  • 实际上,自动调整设置为true的标签将显示省略号,如果其增长受其容器限制(例如:tableLayoutPanel的单元格中的标签) (2认同)

Mic*_*elB 6

我的解决方案

    myLabel.text = Trim(someText, myLabel.Font, myLabel.MaximumSize.Width);

public static string Trim(string text, System.Drawing.Font font, int maxSizeInPixels)
{
    var trimmedText = text;
    var graphics = (new System.Windows.Forms.Label()).CreateGraphics();
    var currentSize = Convert.ToInt32(graphics.MeasureString(trimmedText, font).Width);
    var ratio = Convert.ToDouble(maxSizeInPixels) / currentSize;
    while (ratio < 1.0)
    {
        trimmedText = String.Concat(
           trimmedText.Substring(0, Convert.ToInt32(trimmedText.Length * ratio) - 3), 
           "...");
        currentSize = Convert.ToInt32(graphics.MeasureString(trimmedText, font).Width);
        ratio = Convert.ToDouble(maxSizeInPixels) / currentSize;
    }
    return trimmedText;
}
Run Code Online (Sandbox Code Playgroud)