【发布时间】:2016-02-16 13:44:52
【问题描述】:
我制作了自己的 ComboBox 控件,以便使用具有自定义背景和前景色的项目。 ComboBox 也定义为 DropDownList。
public class CustomComboBox : ComboBox
{
public CustomComboBox()
{
DrawMode = DrawMode.OwnerDrawVariable;
DropDownStyle = ComboBoxStyle.DropDownList;
FlatStyle = FlatStyle.Flat;
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
base.OnDrawItem(e);
e.DrawBackground();
var item = ((ResultColor)Items[e.Index]);
e.Graphics.FillRectangle(item.BackgroundColor, e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height);
e.Graphics.DrawString(item.Name, Font, item.Color, e.Bounds.X, e.Bounds.Y);
e.DrawFocusRectangle();
}
}
如果重要的话,我的 ResultColor 类如下:
public class ResultColor
{
public ResultColor(int id, string name, Brush color, Brush backgroundColor)
{
Id = id;
Name = name;
Color = color;
BackgroundColor = backgroundColor;
}
public int Id { get; set; }
public string Name { get; set; }
public Brush Color { get; set; }
public Brush BackgroundColor { get; set; }
public override string ToString()
{
return Name;
}
}
我遇到的最初问题是,当鼠标悬停在聚焦的项目上时,列表中没有颜色。
进一步环顾四周,我发现我可以使用e.State 来检查当前的项目状态并更改颜色,所以现在我这样做了:
var brush = (e.State & DrawItemState.Focus) == DrawItemState.Focus ?
Brushes.DodgerBlue :
item.BackgroundColor;
e.Graphics.FillRectangle(brush, e.Bounds.X,
e.Bounds.Y, e.Bounds.Width,
e.Bounds.Height);
这样,当我将鼠标悬停在项目上时,它会正确地具有不同的颜色,不幸的是,在我单击/选择一个项目并且组合框关闭后,该项目将保留焦点颜色而不是项目颜色,同样适用于 @ 987654325@ 状态和HotLight 甚至似乎都不起作用,因为它从不触发。
我该如何做到这一点,它只会在下拉菜单打开时悬停在项目上时使用焦点颜色,并在选择项目时使用正确的项目颜色?
【问题讨论】:
标签: c# winforms combobox .net-4.5