65.9K
CodeProject 正在变化。 阅读更多。
Home

调整组合框下拉列表宽度以适应最长字符串宽度

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.56/5 (38投票s)

2004年1月8日

viewsIcon

437826

自动调整组合框下拉列表的宽度,使其与其中最长条目的字符串宽度相匹配。

Sample Image - ComboBoxAutoWidth.jpg

引言

这段小代码片段将向您展示如何自动调整组合框下拉列表的大小,以适应其条目中最大字符串的大小。

代码

步骤 1:为组合框的 DropDown 事件添加一个事件处理程序。为了后续代码的方便,将其命名为 AdjustWidthComboBox_DropDown

步骤 2:添加以下事件处理程序代码。

private void AdjustWidthComboBox_DropDown(object sender, System.EventArgs e)
{
    ComboBox senderComboBox = (ComboBox)sender;
    int width = senderComboBox.DropDownWidth;
    Graphics g = senderComboBox.CreateGraphics();
    Font font = senderComboBox.Font;
    int vertScrollBarWidth = 
        (senderComboBox.Items.Count>senderComboBox.MaxDropDownItems)
        ?SystemInformation.VerticalScrollBarWidth:0;

    int newWidth;
    foreach (string s in ((ComboBox)sender).Items)
    {
        newWidth = (int) g.MeasureString(s, font).Width 
            + vertScrollBarWidth;
        if (width < newWidth )
        {
            width = newWidth;
        }
    }
    senderComboBox.DropDownWidth = width;
}

解释

该代码假定处理程序仅用于 ComboBox,并且在不检查发送者类型的情况下进行强制转换。

然后,它获取组合框的 GraphicsFont 对象,这将帮助我们测量列表中字符串的大小。

senderComboBox.Items.Count>senderComboBox.MaxDropDownItems 检查是否将显示滚动条。如果将显示滚动条,则获取其宽度以相应地调整下拉列表的大小。

然后,我们滚动浏览项目列表,检查每个项目的大小,并最终将下拉列表的宽度设置为最大项目的大小,包括滚动条宽度。

© . All rights reserved.