StyleSelector works for Blind-Style ListBox

The above data-highlighted style is quite commonly used in table, data grid and list box. Today I am gonna implement this style for a list box in WPF

WPF supplies a style selector class, which can be adopted for this situation.

First of all, I need to define two styles for list box items


<Style x:Key=”ListBoxItemAquaStyle” TargetType=”{x:Type ListBoxItem}”>
<Setter Property=”Background” Value=”Aqua”/>
<Style x:Key=”ListBoxItemPurpleStyle” TargetType=”{x:Type ListBoxItem}”>
<Setter Property=”Background” Value=”Purple”/>


Second, I need to extend the basic style selector
public class ListBoxItemStyleSelector : StyleSelector
public override Style SelectStyle(object item, DependencyObject container)
ItemsControl ic = ItemsControl.ItemsControlFromItemContainer(container);
int index = ic.ItemContainerGenerator.IndexFromContainer(container);
Style appliedStyle = null;
if ((index % 2) == 0)
appliedStyle =(Style)ic.FindResource(“ListBoxItemAquaStyle”);
appliedStyle = (Style)ic.FindResource(“ListBoxItemPurpleStyle”);
return appliedStyle;

Third, declare my selector


<local:ListBoxItemStyleSelector x:Key=”ListBoxItemStyleSelector”/>


At last, employ the selector for any listbox.

<ListBox ItemContainerStyleSelector=”{StaticResource ListBoxItemStyleSelector}”>
<sys:String>Martin Wang</sys:String>


For the function of FindResource(Key)

If the resource is not found on the calling element, the parent element in the logical tree is searched next, then the application, then themes, and finally system resources.


Sheva offered another solution, in different way though.


~ by Martin on September 15, 2007.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: