【问题标题】:How to change the color of a listbox item containing a certain string?如何更改包含某个字符串的列表框项的颜色?
【发布时间】:2022-06-10 20:18:27
【问题描述】:

我真的不知道更改某些列表框项目颜色的语法。 我想更改包含某个字符串的列表框中所有项目的颜色。

代码:

string statusG = "Status: (1)";
        for (int i = 0; i < lstBoxResidencies.Items.Count; i++)
        {
            if (lstBoxResidencies.Items[i].ToString().Contains(statusG))
            {
                lstBoxResidencies.Items[i]
            }
        }

【问题讨论】:

  • 您能否编辑您的帖子并粘贴实际代码(不是代码图像)。让它看起来像 code 的技巧是将第一行缩进四个空格。
  • 感谢您的编辑。我已尝试回答您的问题。

标签: c# listboxitem


【解决方案1】:

您的问题是如何更改包含某个字符串的列表框项的颜色,此结果可以通过使用表单设计器更改DrawModeDrawMode 属性来实现@ (例如,OwnerDrawFixed)。在设计器的事件选项卡中,为DrawItem 事件创建一个处理程序。这是代码用于自定义如何绘制项目的地方。我已使用Microsoft Example for the DrawItem Event 并进行了细微更改以适应您的问题:

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    var value = listBox1.Items[e.Index].ToString();

    // Custom-draw the background
    // Here is where you look the the string value.
    if(value.Contains("Status"))
    {
        // Draw custom background
        using (var backgroundBrush = new SolidBrush(Color.Aqua))
        {
            e.Graphics.FillRectangle(backgroundBrush, e.Bounds);
        }
    }
    else
    {
        // Draw default background
        e.DrawBackground();
    }

    // The text must still be drawn.
    // There aren't any real changes so use standard code to do this.
    using (var textBrush = new SolidBrush(listBox1.ForeColor))
    {
        e.Graphics.DrawString(value, listBox1.Font, textBrush, e.Bounds);
    }
}

这显示了自定义绘制的结果:

【讨论】:

  • 1) 您不应该以这种方式覆盖 OnHandleCreated 方法。该方法可能在运行时被多次调用。例如,当您设置调用RecreateHandle 方法的属性时。这意味着,if (!DesignMode) 的同一块可能会再次执行,也可能会再次执行。将其移至ctorForm.Load 事件。 2) 使用TextRenderer.DrawText(...) 方法在控件上绘制字符串并保留Graphics.DrawString 用于图像业务。 3)对于ListBox、ComboBox、CheckedListBox控件,使用GetItemText(...)方法获取item的文本。
  • 好吧,我给你一些尝试。保持您的代码不变,添加一个按钮,处理 Click 事件以设置一个属性,例如通过 RightToLeft 属性切换布局,这会导致句柄重新创建。自己检查结果。
  • 另一个尝试,从ListBox 派生一个新类,覆盖OnHandleCreated 方法并设置DrawMode = DrawMode.OwnerDrawFixed; 属性,它在基类中的设置器调用RecreateHandle 方法。祝你好运:)
猜你喜欢
  • 1970-01-01
  • 2020-12-07
  • 1970-01-01
  • 2018-07-15
  • 1970-01-01
  • 2015-05-17
  • 1970-01-01
  • 1970-01-01
  • 2012-12-16
相关资源
最近更新 更多