Jac*_*i36 0 c# inheritance controls combobox ondraw
我更改了各种控件的突出显示颜色,并计划进行更多更改。因此,我最好创建自己的控件并重用它们,而不是为每个控件进行更改。
我创建了一个新的用户控件,并继承自System.Windows.Forms.ComboBox。问题是我找不到onDraw像我那样的方法来覆盖onClick。
那么我将如何去覆盖它呢?这是我用于每个控制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();
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
干得好:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
您可以在扩展自定义设置时考虑公开更多属性,因此可以在需要时为每个实例更改它们。
另外,不要忘记处理您创建的GDI对象,例如画笔和钢笔!
编辑:刚注意到,这BackColor将隐藏原始属性。将其更改为SelectedBackColor,它实际上说明了什么!
编辑2:正如Simon在评论中所指出的,有一种HasFlag方法,从.Net 4.0开始,还可以编写:
Brush brush = ((e.State.HasFlag(DrawItemState.Selected) ?
Run Code Online (Sandbox Code Playgroud)
这一点更清晰,更短。
编辑3:实际上,TextRenderer.DrawText建议在graphics.DrawString.. 上使用。