Jav*_*ram 69
你不能直接使用它.
做一个技巧
首先遍历组合框的所有项目,通过将文本分配给标签来检查每个项目的宽度.然后,每次检查宽度,如果当前项目的宽度大于先前项目,则更改最大宽度.
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);
}
Run Code Online (Sandbox Code Playgroud)
要么
正如stakx所建议的那样,你可以使用TextRenderer类
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;
}
Run Code Online (Sandbox Code Playgroud)
alg*_*eat 15
这是非常优雅的解决方案.只需将您的组合框订阅到此事件处理程序:
private void AdjustWidthComboBox_DropDown(object sender, EventArgs e)
{
var 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;
var itemsList = senderComboBox.Items.Cast<object>().Select(item => item.ToString());
foreach (string s in itemsList)
{
int newWidth = (int)g.MeasureString(s, font).Width + vertScrollBarWidth;
if (width < newWidth)
{
width = newWidth;
}
}
senderComboBox.DropDownWidth = width;
}
Run Code Online (Sandbox Code Playgroud)
此代码取自codeproject:调整组合框下拉列表宽度到最长字符串宽度.但我已将其修改为使用填充了任何数据(不仅仅是字符串)的组合框.
小智 12
obj.ToString()对我不起作用,我建议使用myCombo.GetItemText(obj).这对我有用:
private int DropDownWidth(ComboBox myCombo)
{
int maxWidth = 0, temp = 0;
foreach (var obj in myCombo.Items)
{
temp = TextRenderer.MeasureText(myCombo.GetItemText(obj), myCombo.Font).Width;
if (temp > maxWidth)
{
maxWidth = temp;
}
}
return maxWidth + SystemInformation.VerticalScrollBarWidth;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
56381 次 |
| 最近记录: |