首先介绍一种简单地方法:就是通过自定义SystemColors类的参数来自定义WPF ListBox选择颜色的,SystemColors的HighlightBrushKey和HighlightTextBrushKey分别代表ListBoxItem被选中时文字和背景颜色,没有Highlight的BrushKey代表ListBox没有焦点时的选中项文字和背景颜色:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 |
<ListBox> <ListBox.Resources> <Style TargetType= "ListBoxItem" > <Style.Resources> <SolidColorBrush x:Key= "{x:Static SystemColors.HighlightBrushKey}"
Color= "Pink" /> <SolidColorBrush x:Key= "{x:Static SystemColors.ControlBrushKey}"
Color= "Gray" /> <SolidColorBrush x:Key= "{x:Static SystemColors.HighlightTextBrushKey}"
Color= "Red" /> <SolidColorBrush x:Key= "{x:Static SystemColors.ControlTextBrushKey}"
Color= "Green" /> </Style.Resources> </Style> </ListBox.Resources> <ListBoxItem>AAA</ListBoxItem> <ListBoxItem>B</ListBoxItem> <ListBoxItem>ccc</ListBoxItem> </ListBox> |
可是这种方法仅仅能改变统一的颜色,无法完成其他更多要求。
那么另一种更强大的方法就是在模板中定义。一种方法就是在控件模板中根据ListBoxItem的IsSelected属性判断是否被选中,然后利用WPF触发器来设置被选中后的样式。但是如果你的ListBox定义了数据模板的话你会发现数据模板是显示在控件模板之上的,因此控件模板上的某些显示元素会被数据模板盖住,如果此类情况发生,那么只能在数据模板上添加选中后的元素设置。这里可以通过一个RelativeBinding = FindAncestor的绑定来寻找可视化树中的ListBoxItem的IsSelected属性来在数据模板中判断ListBoxItem是否被选中。
自定义WPF ListBox的选中项样式,布布扣,bubuko.com
原文:http://www.cnblogs.com/Kingly/p/3660529.html