自定义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中引用该样式就可以~
 
写的不是很清楚,大致思路是这样。不断努力中!
posted on 2012-01-11 17:23  asnow  阅读(1696)  评论(0编辑  收藏  举报