要根据 ListBox 中项的内容来修改字体颜色,你可以在自定义绘制 ListBox 项的过程中添加逻辑来判断项的文本内容,并根据需要设置不同的字体颜色。下面是一个示例代码,演示如何根据文本内容设置 ListBox 中项的字体颜色:

using System;
using System.Drawing;
using System.Windows.Forms;

class CustomListBox : ListBox
{
    protected override void OnDrawItem(DrawItemEventArgs e)
    {
        e.DrawBackground();

        if (e.Index >= 0 && e.Index < Items.Count)
        {
            // 检查项是否被选中
            bool isSelected = (e.State & DrawItemState.Selected) == DrawItemState.Selected;

            // 获取项的文本内容
            string itemText = Items[e.Index].ToString();

            // 根据文本内容设置字体颜色
            Color fontColor;
            if (itemText.Contains('关键词1'))
            {
                fontColor = Color.Red;
            }
            else if (itemText.Contains('关键词2'))
            {
                fontColor = Color.Green;
            }
            else
            {
                fontColor = isSelected ? Color.Blue : Color.Black;
            }

            // 创建一个用于绘制项的矩形
            Rectangle itemRect = new Rectangle(e.Bounds.Left, e.Bounds.Top, e.Bounds.Width, e.Bounds.Height);

            // 填充项的背景色
            using (SolidBrush brush = new SolidBrush(BackColor))
            {
                e.Graphics.FillRectangle(brush, itemRect);
            }

            // 绘制项的文本
            using (SolidBrush brush = new SolidBrush(fontColor))
            {
                e.Graphics.DrawString(itemText, Font, brush, itemRect);
            }
        }

        e.DrawFocusRectangle();
    }
}

class Program
{
    static void Main(string[] args)
    {
        // 创建一个窗口
        Form form = new Form();

        // 创建一个自定义的 ListBox 控件
        CustomListBox listBox = new CustomListBox();
        listBox.Dock = DockStyle.Fill;

        // 添加一些项到 ListBox
        listBox.Items.Add('关键词1');
        listBox.Items.Add('关键词2');
        listBox.Items.Add('Item 3');
        listBox.Items.Add('Item 4');

        // 将 ListBox 添加到窗口中
        form.Controls.Add(listBox);

        // 显示窗口
        Application.Run(form);
    }
}

在示例代码中,我们根据项的文本内容在 OnDrawItem 方法中添加了判断逻辑。如果项的文本内容包含 '关键词1',我们将字体颜色设置为红色。如果文本内容包含 '关键词2',我们将字体颜色设置为绿色。对于其他项,我们保留原来的设置,选中项的字体颜色为蓝色,未选中项的字体颜色为黑色。

你可以根据实际需求和文本内容的不同,添加适当的判断逻辑,并设置不同的字体颜色。

希望这可以帮助你根据 ListBox 中项的内容来修改字体颜色。

C# ListBox 项内容修改字体颜色 - 改变 ListBox 项文本颜色

原文地址: https://www.cveoy.top/t/topic/SDC 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录