WP--listBox選中項顏色改變

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

注意:寫樣式要寫itemcontainer的樣式!!

 
1>字體顏色設置,選中

然後選中states,在selected和unselected的時候分別設置Forground的顏色

 
2>背景色顏色設置:
首先把layoutroot改成grid或者border或是canvas等。

然後和字體顏色改變的方法一樣,分別在selected和unselected的時候分別設置Background的顏色。
最後在xaml中引用該樣式就可以~

發佈了39 篇原創文章 · 獲贊 4 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章