[英]C# Set ListBox width so that longest item fits
我想設置我的 ListBox.Width 屬性,使其不會比需要的更寬或更窄,以便顯示其中的項目。 ListBox 的左側和文本的開頭之間有幾個像素的邊距 - 我希望右側有一個類似的邊距。 (即不應該有很大的間隙,並且字母不應該接觸到右邊緣)。
鑒於我不確定給定的字符串有多少像素,我不確定如何計算這個寬度。
我相信您正在尋找 Graphics 類的 MeasureString 方法。
嘗試這個:
Graphics graphics = this.createGraphics();
SizeF mySize = graphics.MeasureString("Ahoy there", this.Font);
希望這可以幫助!
這對我有用,直到我改變了列表框的寬度,我才看到我想要的結果。 我遍歷列表框中的項目以獲得最長的。 希望這可以幫助。
int LongestItemLength = 0;
for (int i = 0; i < listBox1.Items.Count;i++ ){
Graphics g = listBox1.CreateGraphics();
int tempLength = Convert.ToInt32((
g.MeasureString(
listBox1.Items[i].ToString(),
this.listBox1.Font
)
).Width);
if (tempLength > LongestItemLength){
LongestItemLength = tempLength;
}
}
listBox1.Width = LongestItemLength;
listBox1.Show();
這可能就是你想要的。 還可以使用 Integral Height 和 padding。
http://www.codeproject.com/KB/combobox/resizablelistbox.aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.