C# 设置 ListBox 宽度,以便适合最长的项目
我想设置 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我相信您正在寻找 Graphics 类的 MeasureString 方法。
试试这个:
希望这有帮助!
I believe you're looking for the MeasureString method of the Graphics class.
Try this:
Hope this helps!
这对我有用,直到我更改了列表框的宽度,我才看到了我想要的结果。我循环遍历列表框中的项目以获得最长的项目。希望这有帮助。
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.
这可能就是你想要的。还可以尝试使用整体高度和填充。
This may be what you want. Also play around with Integral Height and padding.
http://www.codeproject.com/KB/combobox/resizablelistbox.aspx