我想将列表框中选定项目的颜色更改为特定的ARGB值。当未选择时,将显示我在列表框的属性中定义的预彩。
但是,无论我尝试什么,都将刷子设置为预定义的颜色(白色,绿色,任何(,选择颜色时,选择&并未以相同颜色选择两者...否则它根本没有改变。我在Stackoverflow上看到的解决方案是基于XAML的,但是我正在使用Winforms c#.net,所以这不是一个选项。
我已经设法制作了已经使用landldrawfix作为drawmode的自定义列表框,并且像这样的自定义绘图词:
{
SolidBrush myBrushBack = new SolidBrush(Color.FromArgb(255, 42, 42, 42));
SolidBrush myBrushFore = new SolidBrush(Color.FromArgb(255, 62, 182, 86));
if (e.Index < 0) return;
e.DrawBackground();
Graphics g = e.Graphics;
Brush brush = ((e.State & DrawItemState.Selected) == DrawItemState.Selected) ?
myBrushBack : new SolidBrush(e.BackColor);
myBrushFore : new SolidBrush(e.ForeColor);
g.FillRectangle(brush, e.Bounds);
SizeF size = e.Graphics.MeasureString(listBoxTracks.ToString(), e.Font);
e.Graphics.DrawString(listBoxTracks.Items[e.Index].ToString(), e.Font,
new SolidBrush(e.ForeColor), e.Bounds.Left + (e.Bounds.Width / 29 - size.Width / 39), e.Bounds.Top + (e.Bounds.Height / 2 - size.Height / 2), StringFormat.GenericDefault);
e.DrawFocusRectangle();
}
此代码没有给我正确的绿色,我想要 它更改了选定的&amp;未选择两者的文本颜色:
e.Graphics.DrawString(listBoxTracks.Items[e.Index].ToString(), e.Font, Brushes.Green, e.Bounds, StringFormat.GenericDefault);
现在的行为:https://i.stack.imgur.com/rfurp.jpg
我希望它的表现:https://i.stack.imgur.com/zuepq.jpg
感谢Jimi,我已经调整了代码,现在使用这样的代码正确起作用:
{
if (e.Index < 0) return;
e.DrawBackground();
bool isItemSelected = ((e.State & DrawItemState.Selected) == DrawItemState.Selected);
using (SolidBrush bgBrush = new SolidBrush(isItemSelected ? Color.FromArgb(255, 42, 42, 42) : Color.FromArgb(255, 29, 29, 29)))
using (SolidBrush itemBrush = isItemSelected ? new SolidBrush(Color.FromArgb(255, 62, 182, 86)) : new SolidBrush(Color.FromArgb(255, 176, 176, 176)))
{
string itemText = listBoxTracks.GetItemText(listBoxTracks.Items[e.Index]);
e.Graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
SizeF size = e.Graphics.MeasureString(listBoxTracks.ToString(), e.Font);
e.Graphics.FillRectangle(bgBrush, e.Bounds);
e.Graphics.DrawString(itemText, e.Font, itemBrush, e.Bounds.Left + (e.Bounds.Width / 29 - size.Width / 39), e.Bounds.Top + (e.Bounds.Height / 2 - size.Height / 2), StringFormat.GenericDefault);
}
e.DrawFocusRectangle();
}