C# 设置 ListBox 宽度,以便适合最长的项目

发布于 2024-11-08 19:29:37 字数 152 浏览 0 评论 0原文

我想设置 ListBox.Width 属性,使其不比需要的更宽或更窄,以便显示其中的项目。列表框左侧和文本开头之间有几个像素的边距 - 我希望右侧也有类似的边距。 (即不应有很大的间隙,并且字母不应接触右边缘)。

鉴于我不确定给定字符串有多少像素,我不确定如何计算这个宽度。

I would like to set my ListBox.Width property so that it is no wider nor narrower than needed, in order to display the items in it. There is a margin of a few pixels between the left of the ListBox and the start of the text - I would like there to be a similar margin on the right. (i.e. there shouldn't be a large gap, and the letters shouldn't be touching the right edge).

Given that I'm not sure how many pixels a given string will be, I'm not sure how to calculate this width.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

蓝天 2024-11-15 19:29:37

我相信您正在寻找 Graphics 类的 MeasureString 方法。

试试这个:

Graphics graphics = this.createGraphics();
SizeF mySize = graphics.MeasureString("Ahoy there", this.Font);

希望这有帮助!

I believe you're looking for the MeasureString method of the Graphics class.

Try this:

Graphics graphics = this.createGraphics();
SizeF mySize = graphics.MeasureString("Ahoy there", this.Font);

Hope this helps!

妖妓 2024-11-15 19:29:37

这对我有用,直到我更改了列表框的宽度,我才看到了我想要的结果。我循环遍历列表框中的项目以获得最长的项目。希望这有帮助。

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(); 

This worked for me, it wasn't until I changed the width of the listbox that I saw the results I wanted. I looped through the items in the listbox to get the longest. Hope this helps.

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(); 
や莫失莫忘 2024-11-15 19:29:37

这可能就是你想要的。还可以尝试使用整体高度和填充。

This may be what you want. Also play around with Integral Height and padding.

http://www.codeproject.com/KB/combobox/resizablelistbox.aspx

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文