Update: There is an update Article. For details, refer to: WPF: Changing the colors of listboxitem and listviewitem.
(: ListBox with Multiple choices)
First, we will introduce a simple method: You can customize the systemcolors class parameters to customize the color of the WPF ListBox. The highlightbrushkey and highlighttextbrushkey of systemcolors indicate the text and background colors when the listboxitem is selected, respectively, brushkey without highlight indicates the selected text and background color when ListBox has no focus:
<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>
In this case, the selected ListBox color is changed to the following:
However, this method can only change the uniform color and cannot meet other requirements.
Another more powerful method is defined in the template. One way is to determine whether the selected style is selected based on the isselected attribute of listboxitem in the control template, and then use the WPF trigger to set the selected style. However, if your ListBox defines a data template, you will find that the data template is displayed on the control template, so some display elements in the control template will be covered by the data template, if this happens, only the selected element settings can be added to the data template. Here, we can use a relativebinding = findancestor binding to find the isselected attribute of listboxitem In the visualization tree to determine whether the listboxitem is selected in the data template.
Source code download
Download Page
Note: the link is the Microsoft SkyDrive page. When downloading, use a browser to download it directly. Some download tools may not be available for downloading.
Source code environment: Microsoft Visual C #2010 Express