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

<Window.Resources>

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

</Window.Resources>

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”);
}
else
{
appliedStyle = (Style)ic.FindResource(“ListBoxItemPurpleStyle”);
}
return appliedStyle;
}

Third, declare my selector

<Window.Resource>

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

</Window.Resource>

At last, employ the selector for any listbox.

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

P.S.

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.

Update:

Sheva offered another solution, in different way though.

Advertisements

~ by Martin on September 15, 2007.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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: