如何通过双击或任何方法更改所选项目的颜色
问题描述:
Hello
I want to change the color of a selected item in ListBox1 by DoubleClick on that item, I drew the items in different colors in formload but I could not change the color of any items after formload ,i tried double click
我尝试了什么:
What I have tried:
private void FormLoad(object sender, EventArgs e)
{
Global_A = 1;
ListBox1.Items.AddRange(new Object[]
{ "Red Item", "Orange Item", "Purple Item" });
ListBox1.Location = new System.Drawing.Point(81, 69);
ListBox1.Size = new System.Drawing.Size(120,95);
ListBox1.DrawMode = DrawMode.OwnerDrawFixed;
ListBox1.DrawItem += new DrawItemEventHandler(ListBox1_DrawItem);
//ListBox1.SelectedIndexChanged += new System.EventHandler(ListBox1_SelectedIndexChanged);
Controls.Add(ListBox1);
Global_A = 2;
Global_id = 2;
}//FormLoad
private void ListBox1_DrawItem(object sender,
System.Windows.Forms.DrawItemEventArgs e)
{
if(e.Index < 0) return;
if (Global_A == 1)
{e.DrawBackground();
Brush myBrush = Brushes.Black;
switch (e.Index)
{
case 0: myBrush = Brushes.Red; break;
case 1: myBrush = Brushes.Orange; break;
case 2: myBrush = Brushes.Purple; break;
}
e.Graphics.DrawString(ListBox1.Items[e.Index].ToString(),
e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);
e.DrawFocusRectangle();
}
else if (Global_A == 2)
{
e.DrawBackground();
Graphics g = e.Graphics;
//Brush myBrush = Brushes.Black;
Brush myBrush2 = Brushes.Red;
//g.FillRectangle(new SolidBrush(Color.Silver), e.Bounds);
//e.Graphics.DrawString(ListBox1.Items[e.Index].ToString(), e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);
e.Graphics.DrawString(ListBox1.Items[id].ToString(),e.Font, myBrush2, e.Bounds, StringFormat.GenericDefault);
e.DrawFocusRectangle();
}//A=2
}
答
你需要设置DrawMode为了触发DrawItem事件:
You need to set the DrawMode in order to fire DrawItem events:
private void FrmMain_Shown(object sender, EventArgs e)
{
myListBox.Items.Add("A - Cyan");
myListBox.Items.Add("B - Magenta");
myListBox.Items.Add("C - Yellow");
myListBox.Items.Add("D - Black");
myListBox.DrawMode = DrawMode.OwnerDrawFixed;
}
private void MyListBox_DrawItem(object sender, DrawItemEventArgs e)
{
if (sender is ListBox lb)
{
e.DrawBackground();
string s = lb.Items[e.Index].ToString();
Brush brush = Brushes.Green;
switch (s[0])
{
case 'A': brush = Brushes.Cyan; break;
case 'B': brush = Brushes.Magenta; break;
case 'C': brush = Brushes.Yellow; break;
case 'D': brush = Brushes.Black; break;
}
e.Graphics.DrawString(s, e.Font, brush, e.Bounds, StringFormat.GenericDefault);
}
}
将以不同方式为每个项目着色。
Will colour each item differently.