Winform重绘ComboBox背景

前言:这篇文章主要是用来解决下拉框样式问题的,当下拉框需要设置成值只能进行选择而不能输入的时候,即设置属性ComboBox.DropDownStyle = ComboBoxStyle.DropDownList;背景颜色就会直接变成灰色,并且没有提供属性可以设置。但是很多时候我们页面上的输入元素都是白色调的,如TextBox,这样看起来就会很突兀,页面也缺乏协调;所以基于此情况,只好通过重新绘制来解决这个问题。.

为了在各个页面方便使用,以下还是通过自定义控件去实现;当然如果不需要也可以,直接对单个控件的OnDrawItem事件进行处理就行。

  1. 新建一个自定义控件,继承自ComboBox,并设置以下属性。

    public partial class ComboBoxEx : ComboBox
     DropDownStyle = ComboBoxStyle.DropDownList; DrawMode = DrawMode.OwnerDrawFixed; ItemHeight = 24;
    
  1. 重写OnDrawItem事件,在此事件中对颜色进行修改

    protected override void OnDrawItem(DrawItemEventArgs e)        {            base.OnDrawItem(e);            if (e.Index >= 0)            {                Brush backgroundBrush = Brushes.White;                Brush foregroundBrush = Brushes.Black;                if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)                {                    backgroundBrush = SystemBrushes.Highlight;                    foregroundBrush = SystemBrushes.HighlightText;                }                e.Graphics.FillRectangle(backgroundBrush, e.Bounds);                string itemText = GetItemText(Items[e.Index]);                e.Graphics.DrawString(itemText, e.Font, foregroundBrush, e.Bounds.X+2, e.Bounds.Y+2);            }        }

实现效果:

Winform重绘ComboBox背景