private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
if (e.Index < 0) return;
// If the item is selected them change the back color.
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
e = new DrawItemEventArgs(e.Graphics,
e.Font,
e.Bounds,
e.Index,
e.State ^ DrawItemState.Selected,
e.ForeColor,
Color.Yellow); // Choose the color.
// Draw the background of the ListBox control for each item.
e.DrawBackground();
// Draw the current item text
e.Graphics.DrawString(listBox1.Items[e.Index].ToString(),e.Font, Brushes.Black, e.Bounds, StringFormat.GenericDefault);
// If the ListBox has focus, draw a focus rectangle around the selected item.
e.DrawFocusRectangle();
}
this.listBox1.DrawMode = DrawMode.OwnerDrawFixed;
this.listBox1.DrawItem += new System.Windows.Forms.DrawItemEventHandler(listBox1_DrawItem);
this.listBox1.SelectedIndexChanged += new System.EventHandler(listBox1_SelectedIndexChanged);
字符串 和事件处理程序:
void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
this.listBox1.Invalidate();
}
void listBox1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
{
int index = e.Index;
Graphics g = e.Graphics;
foreach (int selectedIndex in this.listBox1.SelectedIndices)
{
if (index == selectedIndex)
{
// Draw the new background colour
e.DrawBackground();
g.FillRectangle(new SolidBrush(Color.Red), e.Bounds);
}
}
// Get the item details
Font font = listBox1.Font;
Color colour = listBox1.ForeColor;
string text = listBox1.Items[index].ToString();
// Print the text
g.DrawString(text, font, new SolidBrush(Color.Black), (float)e.Bounds.X, (float)e.Bounds.Y);
e.DrawFocusRectangle();
}
5条答案
按热度按时间vvppvyoh1#
必须重写
Drawitem
事件并将DrawMode
属性设置为DrawMode.OwnerDrawFixed
检查此示例:
字符串
的数据
ccrfmcuu2#
希望这将有助于有人在未来的上述代码帮助我,但不是100%
我仍然有以下问题:
下面解决这个问题
字符串
我还参考了MSDN网站。
yzckvree3#
下面的代码做的正是你所说的:
在InitializeComponent方法中:
字符串
和事件处理程序:
型
代码取自:
http://www.weask.us/entry/change-listbox-rsquo-selected-item-backcolor-net
hvvq6cgz4#
为什么一开始就使用ListBox,而不是用一个完全可定制的单列、无标题可见、只读的DataGridView来代替它呢?
n1bvdmb65#
我也有同样的问题。
不幸的是,我的数组是一个实体类的列表。所以我有相同的代码与上面接受的答案,但有轻微的修改,以选择我的类上的确切属性,我需要在我的列表框的DrawString上:
字符串