自從我今天遇到它以來,我對此問題有了一個解決方案。我的ToolStripStatusLabel被設置爲自動調整大小,但超過了父控件的寬度,因此隱藏自身。我的解決方案專門用於ToolStripStatusLabel控件。由於這種情況,此控件不提供MaxWidth屬性或AutoEllipsis屬性。它也不會爲我生成一個Graphics對象,因爲它不是控件系列的一部分。此方法可以更改爲與兩個Control對象一起使用,除參數外沒有太多變化。我的選擇是相當有限的,所以我製作這個方法:
/// <summary>
/// If a child ToolStripStatusLabel is wider than it's parent then this method will attempt to
/// make the child's text fit inside of the parent's boundaries. An ellipsis can be appended
/// at the end of the text to indicate that it has been truncated to fit.
/// </summary>
/// <param name="child">Child ToolStripStatusLabel</param>
/// <param name="parent">Parent control where the ToolStripStatusLabel resides</param>
/// <param name="appendEllipsis">Append an "..." to the end of the truncated text</param>
public static void TruncateChildTextAccordingToControlWidth(ToolStripStatusLabel child, Control parent, bool appendEllipsis)
{
//If the child's width is greater than that of the parent's
if(child.Size.Width > parent.Size.Width)
{
//Get the number of times that the child is oversized [child/parent]
decimal decOverSized = (decimal)(child.Size.Width)/(decimal)(parent.Size.Width);
//Get the new Text length based on the number of times that the child's width is oversized.
int intNewLength = (int)(child.Text.Length/(2M * decOverSized)); //Doubling as a buffer (Magic Number).
//If the ellipsis is to be appended
if(appendEllipsis) //then 3 more characters need to be removed to make room for it.
intNewLength = intNewLength - 3;
//If the new length is negative for whatever reason
if(intNewLength < 0)
intNewLength = 0; //Then default it to zero
//Truncate the child's Text accordingly
child.Text = child.Text.Substring(0, intNewLength);
//If the ellipsis is to be appended
if(appendEllipsis) //Then do this last
child.Text += "...";
}
}
我將是第一個指出的是,我做了一件可怕的事情,其中包括一個神奇的數字!我很抱歉,但2M是一個緩衝區。我找不到一個更好的方法來做到這一點,當/如果我找到一種方法,我一定會回來,並在這裏更新它。我需要這個神奇數字,因爲我計算的百分比是準確的,但爲了適合父母內部的孩子控制,我需要大約兩倍的回報。
我敢肯定,這取決於標籤字體大小和其他因素不會完全準確,但嘿它的一個開端。
有那麼一刻我以爲這是一個玩笑後,詢問一條繩子有多長... – Oded 2011-04-18 20:18:22
也許你只是需要設置['Label.AutoEllipsis'] (http://msdn.microsoft.com/en-us/library/system.windows.forms.label.autoellipsis.aspx)屬性。 – 2011-04-18 20:19:37
那麼你必須考慮到字母不具有相同的大小(在許多字體中,除了等寬字體):例如'W'並不像'我'那麼小,所以你可以通常不會認爲一個字母數目相同的單詞具有相同的大小。 – 2011-04-18 20:20:27