You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中如何遍历ListBox并单独修改每个项的前景色?

ListBox项前景色设置解决方案

你当前的代码无法修改前景色,核心原因是list_friends.Items[i]获取的是绑定的数据项本身,而非对应的UI控件(ListBoxItem)。要修改前景色,必须先获取每个项对应的ListBoxItem控件,再设置其Foreground属性。

修改后的完整代码如下:

// 需提前引用System.Windows.Media命名空间
for(int i = 0; i < list_friends.Items.Count; i++)
{
    // 获取对应索引的ListBoxItem控件
    ListBoxItem item = list_friends.ItemContainerGenerator.ContainerFromIndex(i) as ListBoxItem;
    if (item != null)
    {
        if (list_friends.Items[i].ToString().Contains("(Online)"))
        {
            item.Foreground = Brushes.Green;
        }
        else
        {
            item.Foreground = Brushes.White;
        }
    }
}

额外注意事项

如果你的ListBox开启了虚拟化(比如使用VirtualizingStackPanel),ContainerFromIndex可能返回null。这种情况下,需要先调用list_friends.ScrollIntoView(list_friends.Items[i])确保目标项被加载,再获取对应的ListBoxItem控件。

内容的提问来源于stack exchange,提问作者SkyZon.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 21:17:10