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.
相关产品推荐
相关产品推荐

