Combobox外观

我可以更改Winforms ComboBox的外观,以便具有DropDownStyle = DropDownList的Combobox看起来更像DropDownStyle = DropDown 。 它们之间的function差异在于前者不允许用户输入值,问题是它的默认颜色方案看起来变灰并且与同一对话框上的文本框不匹配。

您可以通过将DrawMode属性更改为DrawMode.OwnerDrawFixed并自己处理项目绘制来从DropDownList样式获取DropDown外观(幸运的是,这很容易)。 示例类,实现这个想法:

 public class ComboBoxEx : ComboBox { public ComboBoxEx() { base.DropDownStyle = ComboBoxStyle.DropDownList; base.DrawMode = DrawMode.OwnerDrawFixed; } protected override void OnDrawItem(DrawItemEventArgs e) { e.DrawBackground(); if(e.State == DrawItemState.Focus) e.DrawFocusRectangle(); var index = e.Index; if(index < 0 || index >= Items.Count) return; var item = Items[index]; string text = (item == null)?"(null)":item.ToString(); using(var brush = new SolidBrush(e.ForeColor)) { e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; e.Graphics.DrawString(text, e.Font, brush, e.Bounds); } } } 

你可以尝试更改FlatStyle属性,看看你是否得到了更多你喜欢的东西。 如果你真的希望它看起来像将DropDownStyle设置为DropDown ,你可以将DropDownStyle设置为DropDown并吃掉KeyPress事件:

 private void comboBox1_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = true; } 

尽管如此,我可能不会这样做,因为ComboBox的外观是用户的视觉提示,表明他们是否应该能够键入文本区域。