I need to style the first and last items of a list view differently. To achieve that, I started working on a solution based on that answer: Use different template for last item in a WPF itemscontrol
Basically, I have a custom ItemsTemplateSelector that decide on the template to apply based on the item’s index in the list view items (code below).
It works properly except that when the list gets updated (an item is added or removed), the templates do not get selected again (for instance, initially, the SingleItemTemplate gets selected because there is a single item. When I add an item to the list, that first item’s template does not get switched to FirstItemTemplate). How to force template selection for all items?
public class FirstLastTemplateSelector : DataTemplateSelector
{
public DataTemplate DefaultTemplate { get; set; }
public DataTemplate FirstItemTemplate { get; set; }
public DataTemplate LastItemTemplate { get; set; }
public DataTemplate SingleItemTemplate { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
ListView lv = VisualTreeHelperEx.FindParentOfType<ListView>(container);
if (lv != null)
{
if (lv.Items.Count == 1)
{
return SingleItemTemplate;
}
int i = lv.Items.IndexOf(item);
if (i == 0)
{
return FirstItemTemplate;
}
else if (i == lv.Items.Count - 1)
{
return LastItemTemplate;
}
}
return DefaultTemplate;
}
}
As an alternative approach, I would suggest binding the
AlternationCountof yourItemsControlto the number of items in your collection (e.g. theCountproperty). This will then assign to each container in yourItemsControla uniqueAlternationIndex(0, 1, 2, … Count-1). See here for more information:http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.alternationcount.aspx
Once each container has a unique
AlternationIndexyou can use aDataTriggerin your containerStyleto set theItemTemplatebased off of the index. This could be done using aMultiBindingwith a converter that returnsTrueif the index is equal the count,Falseotherwise. Of course you could also build a selector around this approach as well. With the exception of the converter, this approach is nice since it is a XAML only solution.An example using a
ListBox:Where the converter might look something like: