如何更改列表框中所选项目的前景色

mic*_*ohn 4 c# listbox items winforms

我在项目中面临一个小问题,如何更改ListBox. 我可以选择所有项目,ListBox但我不知道如何更改所选项目文本的前景色。

此代码在我的项目中用于选择列表框项目

for (int i = 0; i < lbProductsToBuy.Items.Count; i++)
{
     lbProductsToBuy.SetSelected(i,true);
}
printreceiptToken1();
dataGridView67.Rows.Clear();
Run Code Online (Sandbox Code Playgroud)

谢谢。在这些图像中,您可以看到我的应用程序的 UI。图像 1图像 2。看到最后一张图片,我想更改此选定项目的前景色。

Rez*_*aei 5

您可以设置toDrawMode的属性,然后处理控件的事件并自己绘制项目:ListBoxOwnerDrawFixedDrawItem

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);
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述