自定義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: