2013-03-11 45 views
6

我有一個改變文本的標籤,我希望它是固定長度的單行。每當文本長度超過標籤長度時,我希望它在最後顯示與「...」相符的任何內容。例如:如何使用省略號截斷長字符串的標籤控件?

Some Very Long Text 

會是什麼樣子:

Some Very Lon... 

有誰知道該怎麼做?

回答

13

其中一個選項是將Label.AutoEllipsis設置爲true。

將AutoEllipsis設置爲true可在用戶使用鼠標移過控件時顯示超出標籤寬度的文本。如果AutoSize爲true,則標籤將變長以適應文本,省略號不會出現。

因此,您需要將AutoSize設置爲false。省略號的外觀取決於標籤的固定寬度。 AFAIK,您需要手動處理文本更改以使其取決於文本長度。

+2

實際上自動調整大小的標籤設置爲true,將顯示省略號如果它的增長是由它的容器的限制(例如:在一個TableLayoutPanel中的單元格的標籤) – 2017-03-27 13:28:29

4

我的解決辦法:

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; 
} 
相關問題