自定义listBox选中项的字体颜色以及背景色可以使用2种方法:1)代码中实现;2)写样式。
提要:
您可以使用 ItemContainerGenerator 并基于项的索引来检索项或通过指定数据项来检索容器。例如,如果您有一个绑定了数据的 ItemsControl,并希望基于其索引获取一个项,则可以使用ItemContainerGenerator..::..ContainerFromIndex 方法。如果想检索数据项,可使用 ItemContainerGenerator..::..ItemFromContainer 方法。
1)代码:
listBox的选中项的背景色是实时的,因此在页面中定义一个实时变量 private int _index = -1;
因此在listBox的SelectionChanged事件中,index=-1表示没有选中项,直接选中项赋背景色;index有具体的值,之前的选中项_index恢复到原来的背景色null:
if (_index != -1)
(listData.ItemContainerGenerator.ContainerFromIndex(_index) as ListBoxItem).Background = null;
(listData.ItemContainerGenerator.ContainerFromItem(listData.SelectedItem) as ListBoxItem).Background = new SolidColorBrush(Colors.Red);
_index = listData.SelectedIndex;//获取此次选中项的index
2)style: