问题
I need to show items in a combobox with a different background color. I also want to change what that color is depending on if the item is selected (or the mouse is on top of it), just the same way it works when a combobox is not owner-drawn.
It is all working fine, except that when the mouse comes off one of the items that I changed the color for, the item keeps the same color as when the mouse was on top. In the example below, the item 'other' is initially correctly drawn with myUnselectedBrush; the mouse goes over top, it is correctly drawn with mySelectedBrush; when the mouse comes off, it is incorrectly still drawn with mySelectedBrush; it should have been drawn with myUnselectedBrush. Everything works fine for item 'something', whose color is not altered.
What am I doing wrong?
private void comboBoxDraw(object sender, DrawItemEventArgs e)
{
ComboBox cb = (ComboBox)sender;
Graphics g = e.Graphics;
e.DrawBackground();
if (e.Index > -1)
{
object item = cb.Items[e.Index];
switch (somethingOrOther)
{
case something:
break;
case other:
e.Graphics.FillRectangle(
(cb.SelectedIndex == e.Index)
? mySelectedBrush
: myUnselectedBrush,
e.Bounds);
break;
}
}
}
e.DrawFocusRectangle();
if (e.Index > -1)
{
// draw the string
}
}
回答1:
Rather than using
cb.SelectedIndex == e.Index
I needed to use DrawItemState:
((state & DrawItemState.Selected) > 0) || ((state & DrawItemState.HotLight) > 0)
来源:https://stackoverflow.com/questions/12123015/redrawing-of-owner-drawn-winforms-combobox-items