ComboBox 内容的自动宽度 [英] Auto-width of ComboBox's content

查看:20
本文介绍了ComboBox 内容的自动宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道设置ComboBox 的内容宽度以自动调整大小的方法

Does anybody know a way to set the ComboBox's content's width to autosize

我指的不是 ComboBox 本身,而是打开的内容.

I do not mean the ComboBox itself, just the opened content.

推荐答案

不能直接使用.

做个小把戏

首先遍历组合框的所有项目,通过将文本分配给标签来检查每个项目的宽度.然后,每次检查宽度,如果当前项的宽度大于以前的项,则更改最大宽度.

First iterate through all items of your combobox, check for the width of every items by assigning the text to a label. Then, check width every time, if width of current item gets greater than previous items then change the maximum width.

int DropDownWidth(ComboBox myCombo)
{
    int maxWidth = 0;
    int temp = 0;
    Label label1 = new Label();

    foreach (var obj in myCombo.Items)
    {
        label1.Text = obj.ToString();
        temp = label1.PreferredWidth;
        if (temp > maxWidth)
        {
            maxWidth = temp;
        }
    }
    label1.Dispose();
    return maxWidth;           
}

private void Form1_Load(object sender, EventArgs e)
{
    comboBox1.DropDownWidth = DropDownWidth(comboBox1);
}

<小时>

根据 stakx 的建议,您可以使用 TextRenderer

As suggested by stakx, you can use TextRenderer class

int DropDownWidth(ComboBox myCombo)
{
    int maxWidth = 0, temp = 0;
    foreach (var obj in myCombo.Items)
    {
        temp = TextRenderer.MeasureText(obj.ToString(), myCombo.Font).Width;
        if (temp > maxWidth)
        {
            maxWidth = temp;
        }
    }
    return maxWidth;
}

这篇关于ComboBox 内容的自动宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆