C#实现代码:
1 AutoSizeComboBoxItem#region AutoSizeComboBoxItem
2 /**//// <summary>
3 /// 自动改变CombBox控件下拉框的宽度,
4 /// ComboBox控件的DropDown事件中调用本方法。
5 /// </summary>
6 /// <param name="sender"> ComboBox对象</param>
7 public void AutoSizeComboBoxItem(object sender)
8 {
9 if (sender is ComboBox)
10 {
11
12 Graphics grap = Graphics.FromHwnd((sender as ComboBox).Handle);
13 StringFormat sf = new StringFormat(StringFormat.GenericTypographic);
14 SizeF size;
15 int i = 0;
16 int extraWidth = 4;//额外宽度
17 if ((sender as ComboBox).MaxDropDownItems < (sender as ComboBox).Items.Count)
18 {
19 //可以采用下面三行代码自动获取系统设置的垂直滚动条宽度,单个人觉得过犹不及。 comment by Dominic
20 //VScrollBar vScrollBar = new VScrollBar();
21 //extraWidth += vScrollBar.Width; //取系统垂直滚动条宽度。
22 //vScrollBar.Dispose();
23 extraWidth += 18; //预留18px的滚动条条宽度。
24
25 }
26
27 while (i < (sender as ComboBox).Items.Count)
28 {
29
30 size = grap.MeasureString((sender as ComboBox).Items[i].ToString(), (sender as ComboBox).Font, 500, sf);
31 if (size.Width > (sender as ComboBox).DropDownWidth - extraWidth)
32 {
33 (sender as ComboBox).DropDownWidth = System.Convert.ToInt32(size.Width) + extraWidth;
34
35 }
36 i++;
37
38 }
39
40 grap.Dispose();
41 sf.Dispose();
42 }
43
44 }
45 #endregion //AutoSizeComboBoxItem
46 }
47
2 /**//// <summary>
3 /// 自动改变CombBox控件下拉框的宽度,
4 /// ComboBox控件的DropDown事件中调用本方法。
5 /// </summary>
6 /// <param name="sender"> ComboBox对象</param>
7 public void AutoSizeComboBoxItem(object sender)
8 {
9 if (sender is ComboBox)
10 {
11
12 Graphics grap = Graphics.FromHwnd((sender as ComboBox).Handle);
13 StringFormat sf = new StringFormat(StringFormat.GenericTypographic);
14 SizeF size;
15 int i = 0;
16 int extraWidth = 4;//额外宽度
17 if ((sender as ComboBox).MaxDropDownItems < (sender as ComboBox).Items.Count)
18 {
19 //可以采用下面三行代码自动获取系统设置的垂直滚动条宽度,单个人觉得过犹不及。 comment by Dominic
20 //VScrollBar vScrollBar = new VScrollBar();
21 //extraWidth += vScrollBar.Width; //取系统垂直滚动条宽度。
22 //vScrollBar.Dispose();
23 extraWidth += 18; //预留18px的滚动条条宽度。
24
25 }
26
27 while (i < (sender as ComboBox).Items.Count)
28 {
29
30 size = grap.MeasureString((sender as ComboBox).Items[i].ToString(), (sender as ComboBox).Font, 500, sf);
31 if (size.Width > (sender as ComboBox).DropDownWidth - extraWidth)
32 {
33 (sender as ComboBox).DropDownWidth = System.Convert.ToInt32(size.Width) + extraWidth;
34
35 }
36 i++;
37
38 }
39
40 grap.Dispose();
41 sf.Dispose();
42 }
43
44 }
45 #endregion //AutoSizeComboBoxItem
46 }
47
在ComboBox的DropDown事件中调用这个函数就可以了。
我将它写入到一个UIhelper类中,调用。
//仅供参考。