【问题标题】:C# Set ListBox width so that longest item fitsC# 设置 ListBox 宽度,以便最长的项目适合
【发布时间】:2011-05-19 01:39:30
【问题描述】:

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

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

【问题讨论】:

    标签: c# winforms listbox


    【解决方案1】:

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

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

    【讨论】:

    • 为什么每次循环迭代都调用CreateGraphics()?此外,您不会处理您创建的 Graphics 对象。对于Graphics.MeasureString(),我相信任何Graphics 对象都可以!无需重新创建。
    【解决方案2】:

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

    试试这个:

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

    希望这会有所帮助!

    【讨论】:

      【解决方案3】:

      这可能是你想要的。还可以使用 Integral Height 和 padding。

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

      【讨论】:

      • 我的链接实现了@Fishz 的答案。
      猜你喜欢
      • 2011-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-22
      相关资源
      最近更新 更多