自定义WPF ListBox的选择样式

来源:互联网 发布:菜鸟网络借壳三泰控股 编辑:程序博客网 时间:2024/05/19 21:59

http://winsystem.ctocio.com.cn/407/12166907.shtml

(下图:进行多项选择的ListBox)

image

  首先介绍一种简单地方法:就是通过自定义SystemColors类的参数来自定义WPF ListBox选择颜色的,SystemColors的HighlightBrushKey和HighlightTextBrushKey分别代表ListBoxItem被选中时文字和背景颜色,没有Highlight的BrushKey代表ListBox没有焦点时的选中项文字和背景颜色:

以下是代码片段:

<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>

  这样的话,ListBox选中颜色变成了这样:

image

  可是这种方法仅仅能改变统一的颜色,无法完成其他更多要求。

  那么另一种更强大的方法就是在模板中定义。一种方法就是在控件模板中根据ListBoxItem的IsSelected属性判断是否被选中,然后利用WPF触发器来设置被选中后的样式。但是如果你的ListBox定义了数据模板的话你会发现数据模板是显示在控件模板之上的,因此控件模板上的某些显示元素会被数据模板盖住,如果此类情况发生,那么只能在数据模板上添加选中后的元素设置。这里可以通过一个RelativeBinding = FindAncestor的绑定来寻找可视化树中的ListBoxItem的IsSelected属性来在数据模板中判断ListBoxItem是否被选中。

原创粉丝点击