覆盖ComboBox的DrawItem

我更改了各种控件的高亮颜色,我打算进行更多更改。 因此,我最好创建自己的控件并重用它们,而不是为每个控件进行更改。

我创建了一个新的用户控件,并inheritance自System.Windows.Forms.ComboBox 。 问题是我无法像onClick那样找到覆盖onDraw的方法。

那我该如何去改写呢? 这是我用于每个控件onDraw事件的代码

 public void comboMasterUsers_DrawItem(object sender, DrawItemEventArgs e) { e.DrawBackground(); Graphics g = e.Graphics; Brush brush = ((e.State & DrawItemState.Selected) == DrawItemState.Selected) ? Brushes.LightSeaGreen : new SolidBrush(e.BackColor); g.FillRectangle(brush, e.Bounds); e.Graphics.DrawString(comboMasterUsers.Items[e.Index].ToString(), e.Font, new SolidBrush(e.ForeColor), e.Bounds, StringFormat.GenericDefault); e.DrawFocusRectangle(); } 

谢谢!

干得好:

 public class myCombo : ComboBox { // expose properties as needed public Color SelectedBackColor{ get; set; } // constructor public myCombo() { DrawItem += new DrawItemEventHandler(DrawCustomMenuItem); DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; SelectedBackColor= Color.LightSeaGreen; } protected void DrawCustomMenuItem(object sender, DrawItemEventArgs e) { e.DrawBackground(); // a dropdownlist may initially have no item selected, so skip the highlighting: if (e.Index >= 0) { Graphics g = e.Graphics; Brush brush = ((e.State & DrawItemState.Selected) == DrawItemState.Selected) ? new SolidBrush(SelectedBackColor) : new SolidBrush(e.BackColor); Brush tBrush = new SolidBrush(e.ForeColor); g.FillRectangle(brush, e.Bounds); e.Graphics.DrawString(this.Items[e.Index].ToString(), e.Font, tBrush, e.Bounds, StringFormat.GenericDefault); brush.Dispose(); tBrush.Dispose(); } e.DrawFocusRectangle(); } } 

您可以考虑在展开自定义时公开更多属性,以便在需要时为每个实例更改它们。

另外,不要忘记处理您创建的GDI对象,如画笔和笔!

编辑:刚刚注意到BackColor会隐藏原始属性。 将其更改为SelectedBackColor ,实际上说它是什么!

编辑2:正如Simon在评论中指出的那样,有一个HasFlag方法,因此.Net 4.0也可以写:

  Brush brush = ((e.State.HasFlag(DrawItemState.Selected) ? 

这更清晰,更短。