【问题标题】:Change color of Listbox Item based on condition根据条件更改列表框项的颜色
【发布时间】:2019-02-20 09:22:51
【问题描述】:

我正在尝试根据条件更改列表框中线条的颜色。列表框正在显示一个列表对象,它是名称,然后它会计算该人未来日期的年龄。

如果他们小于 5 岁或介于 6 到 18 岁之间,我正在尝试设置线条的颜色。

DateTime futureDate = dateTimePicker3.Value;

        foreach (ChildDetails c in children)
        {
            int Age = futureDate.Year - c.DOB.Year;

            if (c.DOB > futureDate.AddYears(-Age))
            {
                Age--;
            }

            if (Age <= 5)
            {
                this.listBox4.ForeColor = Color.Yellow;
            }
            else if (Age >= 6 && Age <= 18)
            {
                this.listBox4.ForeColor = Color.Green;
            }
            else
            {
                this.listBox4.ForeColor = Color.Red;
            }

            listBox4.Items.Add($" {c.name} {Age}");            
        }

【问题讨论】:

  • 这里有什么问题?
  • WinForms 还是 WPF?添加标签。

标签: c# .net


【解决方案1】:

如果您改用ListView,您可以指定每个项目的Forecolor(和/或Backcolor)。例如,在您的表单上添加ListView 并尝试以下代码:

private void Form1_Load(object sender, EventArgs e)
{
    listView1.View = View.List;
    var items = new Dictionary<string, int>
    {
        {"Shaggy", 4},
        {"Fred", 6},
        {"Daphne", 10},
        {"Velma", 16},
        {"Scooby", 20},
    };

    foreach (var item in items)
    {
        int age = item.Value;
        Color foreColor;
        Color backColor;

        if (age <= 5)
        {
            foreColor = Color.Yellow;
            backColor = Color.Purple;
        }
        else if (age >= 6 && age <= 18)
        {
            foreColor = Color.Green;
            backColor = Color.BurlyWood;
        }
        else
        {
            foreColor = Color.Red;
            backColor = Color.CornflowerBlue;
        }

        listView1.Items.Add(new ListViewItem
        {Text = item.Key, ForeColor = foreColor, BackColor = backColor});
    }
}

输出

【讨论】:

  • 你明白我使用列表框的原因是因为我从中选择了在另一个选项卡中打开的东西。但是我确实在不需要列表框的地方使用了您的代码,并使用了列表视图并且效果很好,谢谢
【解决方案2】:

只需创建一个 listboxItem 并更改该 listBoXItem 的前景色或背景色,然后将其插入到 listbox 中。 here is a link that can help you

【讨论】:

    猜你喜欢
    • 2017-05-20
    • 2013-08-28
    • 1970-01-01
    • 1970-01-01
    • 2021-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-22
    相关资源
    最近更新 更多