[英]How to change the color of a selected item in a listbox to a specific ARGB value?
我想將列表框中所選項目的顏色更改為特定的ARGB值。 如果沒有選中,它會顯示我在listBox的屬性中定義的ForeColor。
但無論我嘗試它,要么將畫筆設置為預定義的顏色(白色,綠色,等等),在選擇時更改顏色,而不是以相同顏色選擇兩者......或者它根本不變。 我在stackoverflow上看到的解決方案是基於XAML的,但我使用的是Winforms C#.NET,因此這不是一個選項。
我已經設法使用OwnerDrawFixed作為DrawMode創建一個自定義listBox和一個預定義的自定義DrawItem,如下所示:
{
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();
}
這段代碼沒有給我正確的綠色我想要+它改變了兩者的選定和未選擇的文本顏色:
e.Graphics.DrawString(listBoxTracks.Items[e.Index].ToString(), e.Font, Brushes.Green, e.Bounds, StringFormat.GenericDefault);
它現在的表現如何: https : //imgur.com/a/VvhDjqQ
我希望它如何表現: https : //imgur.com/a/IqNT70p
感謝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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.