winform自定义ComboBox,用于下拉框内容多显示不全问题。
在OnDropDown事件中,改变DropDownWidth。
public class CustomerCombox : ComboBox
{
protected override void OnDropDown(EventArgs e)
{
base.OnDropDown(e);
AdjustComboBoxDropDownListWidth();
}
private void AdjustComboBoxDropDownListWidth()
{
this.DropDownWidth = this.Width;
int vertScrollBarWidth = (this.Items.Count > this.MaxDropDownItems) ? SystemInformation.VerticalScrollBarWidth : 0;
int maxWidth = this.DropDownWidth;
foreach (var layouts in this.Items)
{
int measureTextWidth = TextRenderer.MeasureText(layouts.ToString(), this.Font).Width;
maxWidth = maxWidth < measureTextWidth ? measureTextWidth : maxWidth;
}
this.DropDownWidth = maxWidth + vertScrollBarWidth;
}
}