如何在ListBox中更改SelectedItem的ForeColor [英] How to change ForeColor of SelectedItem in ListBox
问题描述
我在项目中遇到一个小问题,如何更改ListBox
中所选项目的文本的原色.我可以选择ListBox
的所有项目,但是我不知道如何更改所选项目的文本的原色.
I am facing a little issue in my project how can I change fore-color of text of selected items in ListBox
. I can select all items of ListBox
but I don't know how to change fore-color of text of selected items.
此代码正在我的项目中用于选择列表框项目
This code am using in my project for select listbox items
for (int i = 0; i < lbProductsToBuy.Items.Count; i++)
{
lbProductsToBuy.SetSelected(i,true);
}
printreceiptToken1();
dataGridView67.Rows.Clear();
谢谢.在这些图像中,您可以看到我的应用程序的UI. image1 和
Thanks. In these images you can see UI of my application. image1 and image2. See this last image, I want to change this selected items fore-color.
推荐答案
您可以设置控件的DrawItem
事件并自己绘制项目:
You can set DrawMode
property of ListBox
to OwnerDrawFixed
and then hanlde DrawItem
event of the control and draw items yourself:
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
var listBox = sender as ListBox;
var backColor = this.BackColor; /*Default BackColor*/
var textColor = this.ForeColor; /*Default ForeColor*/
var txt = listBox.GetItemText(listBox.Items[e.Index]);
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
{
backColor = Color.RoyalBlue; /*Seletion BackColor*/
textColor = Color.Yellow; /*Seletion ForeColor*/
}
using (var brush = new SolidBrush(backColor))
e.Graphics.FillRectangle(brush, e.Bounds);
TextRenderer.DrawText(e.Graphics, txt, listBox.Font, e.Bounds, textColor,
TextFormatFlags.VerticalCenter | TextFormatFlags.Left);
}
这篇关于如何在ListBox中更改SelectedItem的ForeColor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!